在使用ECMA从node.js中的另一个文件导入函数时出现错误



我想从callModule导出我的app.js中的这2个函数。MJS,但在这样做的时候,我总是得到以下错误:

import {showUsers, callUserProfile} from "./callModule.mjs"
^
SyntaxError: Unexpected token {
at Module._compile (internal/modules/cjs/loader.js:723:23)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
at Module.load (internal/modules/cjs/loader.js:653:32)
at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
at Function.Module._load (internal/modules/cjs/loader.js:585:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:831:12)
at startup (internal/bootstrap/node.js:283:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:623:3)

这是我的app.js

import {showUsers, callUserProfile} from "./callModule.mjs"
showUsers();
callUserProfile();

这是我的callModule.mjs

function showUsers(){
console.log("this is show users function");
}
function callUserProfile(){
console.log("This is user profile function");
}
export {showUsers, callUserProfile}

这里是我的package.json

{
"name": "node-project",
"version": "1.0.0",
"description": "It is a beginner project for node js.",
"main": "index.js",
"type": "module",
"scripts": {
"test": "echo "Error: no test specified" && exit 1"
},
"author": "manish agarwal",
"license": "ISC",
"dependencies": {
"@angular/cli": "^12.2.11",
"express": "^4.17.1"
}
}

谁能建议我在这里做错了什么,因为我是Node的新手。

感谢

您可以使用esm包:

  1. Install esm:npm install --save esm
  2. 使能esm:node -r esm index.js

更多信息&文档:https://www.npmjs.com/package/esm

最新更新