问题
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:
- Node version >= 14. It only works with latest version of node.
- 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