首页 > 解决方案 > 如何从终端运行 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命令构建它。现在我创建了 localtest.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)

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

标签: javascriptnode.jstypescript

解决方案


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

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

更多信息:


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


推荐阅读