如何从终端运行 esnext 文件



我有点新打字稿,我写了一个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"]
}

我使用tsc命令构建它。现在我创建了本地测试.js文件,我正在导入它

import getWorkspace from './lib/index'
const randomFunc = async () => {
// some code 
}
randomFunc()

然后在我的终端中使用以下命令运行它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)

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

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

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

更多信息:

  • https://nodejs.org/dist/latest-v12.x/docs/api/esm.html#esm_enabling
  • https://stackoverflow.com/a/45854500/6003547

或者,您可以将"模块"编译器选项更改为"commonjs"以发出requires。

Node 支持这一点,但它仍然是实验性的。您需要设置一些内容。

  1. 您需要 Node.js版本 12+
  2. 您需要一个标志--experimental-modules并设置为使用它。
  3. type更改为package.json中的module
node --experimental-modules localtest.js
// package.json
{
"type": "module"
}

您可以在此处阅读有关此内容的文档。

最新更新