如何从终端运行esnext文件

ann*_*123 5 javascript node.js typescript

我有点新打字稿,我写了一个 SDK,我的 .tsconfig 看起来有点像这样

{
  "compilerOptions": {
    "moduleResolution": "node",
    "experimentalDecorators": true,
    "module": "esnext",
    "noImplicitReturns": true,
    "noUnusedLocals": true,
    "sourceMap": true,
    "strict": true,
    "target": "es2015",
    "resolveJsonModule": true,
    "esModuleInterop": true,
    "noImplicitAny": false,
    "outDir": "./lib",
  },
  "compileOnSave": true,
  "include": [
    "src"
  ],
  "exclude": ["node_modules"]
}
Run Code Online (Sandbox Code Playgroud)

我使用tsc命令构建它。现在我创建了 localtest.js 文件,我在其中导入了这个文件

import getWorkspace from './lib/index'

const randomFunc = async () => {
   // some code 
}
randomFunc()
Run Code Online (Sandbox Code Playgroud)

然后在我的终端中使用以下命令运行它node localtest.js会引发以下错误

function (exports, require, module, __filename, __dirname) { import getWorkspace from './lib/index'
                                                                     ^^^^^^^^^^^^

SyntaxError: Unexpected identifier
    at new Script (vm.js:80:7)
    at createScript (vm.js:274:10)
    at Object.runInThisContext (vm.js:326:10)
    at Module._compile (internal/modules/cjs/loader.js:664:28)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:712:10)
    at Module.load (internal/modules/cjs/loader.js:600:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:539:12)
    at Function.Module._load (internal/modules/cjs/loader.js:531:3)
    at Function.Module.runMain (internal/modules/cjs/loader.js:754:12)
    at startup (internal/bootstrap/node.js:283:19)
Run Code Online (Sandbox Code Playgroud)

关于如何修复它以及为什么会出现上述错误的任何想法

has*_*rus 3

默认情况下,Node 不接受.js文件中的 ES6 导入。

  • 在节点 12 上,添加--experimental-modules标志。如果它较低——你就必须升级。
  • 要么将扩展名更改为.mjs,要么...
  • 要在文件中使用 ESModule .js(如 TS 发出的文件),请添加"type": "module"到最近的 package.json。

更多信息:


或者,您可以将“module”编译器选项更改为“commonjs”以发出requires。