javascript - 如何从终端运行 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)
关于如何修复它以及为什么会出现上述错误的任何想法
解决方案
.js
默认情况下,Node 不接受文件中的 ES6 导入。
- 在节点 12 上,添加
--experimental-modules
标志。如果它更低 - 你必须升级。 - 将扩展名更改为
.mjs
, 或... - 要在文件中使用 ESModules
.js
(如 TS 发出的文件),请添加"type": "module"
到最近的 package.json。
更多信息:
- https://nodejs.org/dist/latest-v12.x/docs/api/esm.html#esm_enabling
- https://stackoverflow.com/a/45854500/6003547
或者,您可以将“module”编译器选项更改为“commonjs”以发出require
s。
推荐阅读
- java - 为服务创建测试
- android - Android Studio 中显示的 Android 设备列表卡住了
- javascript - 格式化货币显示货币名称而不是符号
- python - 如何在使用正则表达式在 Python 中查找模式时转义 \triangle、\bold 等
- c - 打印函数,C语言中的hello world
- database - 在 MSQ 数据中查找 MILL
- microsoft-graph-api - 在团队自定义应用程序中,隐藏/显示静态选项卡选项
- python - Keras LSTM 花了很长时间才开始拟合
- java - 在 UserDetailsService 中使用 @Cacheable 时为空编码密码
- javascript - 显示重音字符忽略额外的反斜杠