首页 > 解决方案 > 使用 ECMA 从 node.js 中的另一个文件导入函数时出错

问题描述

我想在我的 app.js 中从 callModule.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.js 的新手。

谢谢

标签: node.jsecmascript-6

解决方案


您可以使用esm包:

  1. 安装 esm:npm install --save esm
  2. 启用 esm:node -r esm index.js

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


推荐阅读