【问题标题】:How to run esnext file from terminal如何从终端运行 esnext 文件
【发布时间】:2020-05-09 17:47:36
【问题描述】:

我是一个新的打字稿,我写了一个 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)

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

【问题讨论】:

  • 这甚至不是合法的 ES 6:导入和导出必须是顶级语句。您不能在函数内部执行此操作。为什么它必须是 ES 6 模块?

标签: javascript node.js typescript


【解决方案1】:

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

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

更多信息:


或者,您可以将"module" compiler option 更改为“commonjs”以发出requires。

【讨论】:

    【解决方案2】:

    Node 支持此功能,但仍处于试验阶段。您需要设置一些东西。

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

    您可以阅读有关此here 的文档。

    【讨论】:

      猜你喜欢
      • 2013-06-05
      • 2015-02-28
      • 2017-09-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-12
      • 1970-01-01
      • 2013-11-07
      相关资源
      最近更新 更多