Cannot use import statement outside modules - node js express

node exprss写代码

//example.js
import { xxx } from '@aaa'
aaa = new aaa();
...

// 其它使用的地方 ,例如 app.js,会出错 Cannot use import statement outside modules
require('./example.js')

需要将 example.js 改为 example.mjs
然后将 require改为 import('./example.mjs'); 就可以编译了

---- 原因如下, 参考 https://stackoverflow.com/questions/60392949/cannot-use-import-statement-outside-modules
Since Node v12, you can use either the .mjs extension or set "type": "module" in your package.json.
Node 12版本后,使用

And you need to run node with the --experimental-modules flag.

node --experimental-modules server.mjs
You can check the SO link

Or you can create .babelrc file in the root of your project. Add following (and any other babel presets you need, can be added in this file):

{
"presets": ["env"]
}
Install babel-preset-env using

npm install babel-preset-env
npm install babel-cli -g

OR

yarn add babel-preset-env
yarn global add babel-cli
Now, go to the folder where your server.js file exists and

run using:

babel-node fileName.js
Or you can run using npm start by adding following code to your package.json file:

"scripts": {
"start": "babel-node server.js"
}
There is a tutorial link for Set Up Next.js with a Custom Express Server + Typescript on a medium that will be very helpful for you.

posted @ 2021-11-27 17:15  正版软件开发  阅读(123)  评论(0)    收藏  举报