![](/img/trans.png)
[英]Executing typescript code using ts-node gives “Cannot use import statement outside a module” error
[英]Issues compiling nodejs code with ts-node (Cannot use import statement outside a module)
尝试使用以下命令使用 NodeJS 编译 typescript 代码时:
npx ts-node src/server.ts
我收到以下错误:
SyntaxError: Cannot use import statement outside a module
我按照错误提示的说明进行操作:
警告:要加载 ES 模块,请在 package.json 中设置“type”:“module”或使用 .mjs 扩展名。
但是在遵循这些之后,我仍然没有运气,而是抛出了另一个错误。
这是我的 server.ts 文件的内容。
import App from './app';
const app = new App();
app.listen(3080);
tsconfig.json 内容:
{
"compileOnSave": false,
"compilerOptions": {
"target": "ES2017",
"lib": ["es2017"],
"typeRoots": ["node_modules/@types"],
"allowSyntheticDefaultImports": true,
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"forceConsistentCasingInFileNames": true,
"module": "commonjs",
"pretty": true,
"sourceMap": true,
"declaration": true,
"outDir": "./dist",
"allowJs": true,
"noEmit": false,
"esModuleInterop": true,
"resolveJsonModule": true,
"importHelpers": true,
"baseUrl": "src",
"skipLibCheck": true,
"paths": {
"@/*": ["*"],
}
},
"include": ["src/**/*.ts", "src/**/*.json", ".env"],
"exclude": ["node_modules"]
}
我不确定是什么原因造成的,但非常感谢您在这个问题上的一些智慧。
理想情况下,我想通过 server.ts 文件加载应用程序,同时维护 TypeScript 内容。
您可能需要compilerOptions
中的"moduleResolution": "node"
来让 ts 识别这些类型的导入。
赛斯的回答是 100%。 尽管事实证明 React 正在用自己的配置替换 Typescript 配置。 我已经对其进行了扩展并修改了扩展以替换 React 的配置。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.