Yuav ua li cas mus kho cov ntawm JS “SyntaxError: Npaj txhij txog token ntshuam” thaum uas siv cov JavaScript modules
Nyob rau hauv kev txiav txim rau ntawm rau export modules koj yuav tsum muab txhua muaj nuj nqi, yam khoom los yog nce mus nce los, uas yuav tsum tau yuav tsum tau exported, raws li thaj chaw ntawm lub modules.exports kwv.
exporting
In this example the module file is robot.js. Each function, yam khoom los yog nce mus nce los peb xav ua kom muaj mus rau lwm cov ntaub ntawv peb ua rau lawv thaj chaw ntawm lub export khoom.
robot.js (module cov ntaub ntawv)
exports.sayHello = (msg) => console.log('Nyob zoo peeps!') exports.hello = "Nyob zoo!" exports.greetings = { lus Askiv : "Nyob zoo!", Fabkis txoj : "Nyob zoo!", spanish: "Ola!" }
importing
Ntawm tsis txhawb cov ntshuam nqe lus, yog li ntawd cov laus yuav tsum tau muaj nuj nqi yuav tsum tau siv thaum importing.
Ntawm no yog peb import robot.js (ceeb toom: .js yuav optionally yuav tshuav tawm nyob rau hauv lub yuav tsum tau muaj nuj nqi) and assign it to an object that we can name anything. We name it robot. Our robot object now holds our exported modules from robot.js
Peb yuav siv nws raws li nram no…
app.js (ntsiab ntaub ntawv)
const neeg hlau = yuav tsum tau('./robot') robot.sayHello() console.log(robot.hello) console.log(robot.greetings.french)
Nco ntsoov siv tus kwv lub npe uas koj xaiv rau ntawm thawj kab thaum siv koj cov module nce mus nce los, muaj nuj nqi los yog yam khoom.
Ceeb toom: Browsers do not support the require statement. Therefore you cannot use the require import module function with browsers without using a transpiler such as Babel or a bundler such as Browserify.