1

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...

main.js import part

import dropDownList from "./navigationList.json"; //This is line number 1

console.log(dropDownList.shop.kits);

navigationList.json file

{
    "shop": {
        "kits": "DIY Physics Kits",
        "merch": "Merchendise"
    },

    "learn": {
        "first-sub": "Mechanics",
        "second-sub": "Miscellaneous"
    }
}

Error the console is showing:

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

4

2 回答 2

3

import语法是 ES6 模块的一部分。看起来您正在使用 Node.js,默认情况下它不包括对 ES6 模块的支持。然而,Node.js 对 ES6 模块有实验性的支持

  1. 重命名文件以具有.mjs扩展名:
mv mainJS.js mainJS.mjs
  1. --experimental-modules使用标志运行它:
node --experimental-modules mainJS.mjs

我用你的代码对此进行了测试,它可以工作:

% node --experimental-modules main.mjs
(node:73044) ExperimentalWarning: The ESM module loader is experimental.
DIY Physics Kits

在撰写本文时,我使用的是 Node.js v12.3.1:

% node --version
v12.3.1

或者,您可以使用像 Babel 这样的工具来转换您的代码,它将 s 更改importrequires。

于 2019-05-28T19:13:33.563 回答
1

导航列表.json

{
    "shop": {
        "kits": "DIY Physics Kits",
        "merch": "Merchendise"
    },

    "learn": {
        "first-sub": "Mechanics",
        "second-sub": "Miscellaneous"
    }
}

main.js

var navigation_list = require('./navigation_list.json');
console.log(`>>>> Returned JSON data: ${navigation_list.shop.kits}`);

在这里结束输出:

于 2019-05-28T20:11:03.070 回答