nodejs使用import报错

nodejs使用import报错:

导出模块:

//D:/workspace/www/hello-world/src/data/articles.js

const articles = [
    {"title": "title1","content": "content1"},
    {"title": "title2","content": "content2"},
    {"title": "title3","content": "content3"}]

export default articles;

导入模块:

//D:/workspace/www/nodejs_scripts/test.js

import articles from 'D:/workspace/www/hello-world/src/data/articles';

console.log(articles);

在命令行中运行test.js,报错:

D:\workspace\www\nodejs_scripts
λ node -v
v12.11.1

D:\workspace\www\nodejs_scripts
λ node test.js
D:\workspace\www\nodejs_scripts\test.js:3
import articles from 'D:/workspace/www/hello-world/src/data/articles';
^^^^^^

SyntaxError: Cannot use import statement outside a module
    at Module._compile (internal/modules/cjs/loader.js:881:18)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:962:10)
    at Module.load (internal/modules/cjs/loader.js:798:32)
    at Function.Module._load (internal/modules/cjs/loader.js:711:12)
    at Function.Module.runMain (internal/modules/cjs/loader.js:1014:10)
    at internal/main/run_main_module.js:17:11

应该怎么做呢?

阅读 30.6k
2 个回答

需要在运行 node 时加 --experimentabl-modules 参数,并且扩展名是 mjs ,或者在 package.json 里相应设置,才可以在 node 里使用 ES module 。

详见文档

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题