I can't import anything in my javascript files of my website, I've tried many things but it doesn't work.
So I want to import a .json file to a .js file using the import
key word but it doesn't work. Another problem is that Visual Studio Code doesn't show me an error but the console does...
import dropDownList from "./navigationList.json"; //This is line number 1
console.log(dropDownList.shop.kits);
{
"shop": {
"kits": "DIY Physics Kits",
"merch": "Merchendise"
},
"learn": {
"first-sub": "Mechanics",
"second-sub": "Miscellaneous"
}
}
mainJS.js:1 Uncaught SyntaxError: Unexpected identifier
The console says there is an Uncaught SyntaxError with my import and this causing me to make my code long and without import which sucks. Please help me
The import
syntax is part of ES6 modules. It looks like you are using Node.js, which does not include support for ES6 modules by default. However, Node.js has experimental support for ES6 modules.
.mjs
extension:mv mainJS.js mainJS.mjs
--experimental-modules
flag:node --experimental-modules mainJS.mjs
I tested this with your code, and it works:
% node --experimental-modules main.mjs
(node:73044) ExperimentalWarning: The ESM module loader is experimental.
DIY Physics Kits
At the time of this writing, I am using Node.js v12.3.1:
% node --version
v12.3.1
Alternatively, you can transpile your code with a tool like Babel, which changes import
s to require
s.