NodeJS “Must use import to load ES Module”

六月ゝ 毕业季﹏ 提交于 2021-01-02 08:44:11

问题


I'm trying to import myArr from hello.js into index.js. However I get an error of

Error [ERR_REQUIRE_ESM]: Must use import to load ES Module

hello.js

export let myArr = ['hello', 'hi', 'hey'];

index.js

import { myArr } from './hello.js'
console.log(myArr)

Where am I going wrong?


回答1:


The problem is that node does not currently support import and export natively yet. It is still experimental according to the docs. I recommend you use babel to compile your code and allow you to use import and export.

For example, you can install the @babel/node package and run your project using:

npx babel-node index.js

Here are the docs for @babel/node. Like the docs state, this command is only meant for local development. In production, they recommend a configuration like this. Happy coding!




回答2:


I ran your code with no problem. Check for 2 things:

  1. Node version >= 14. It only works with latest version of node.
  2. Make sure your package.json includes a line for "type": "module", Without this line node assumes you want to use Common JS modules rather than ESM.



回答3:


you should use

module.exports.myArr = ['hello', 'hi', 'hey'];

as your export statement

edit: and use

const {myArr} = require('./hello.js')

as an import



来源:https://stackoverflow.com/questions/61670459/nodejs-must-use-import-to-load-es-module

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!