[英]Issues compiling nodejs code with ts-node (Cannot use import statement outside a module)
When attempting to compile typescript code with NodeJS using the following command:尝试使用以下命令使用 NodeJS 编译 typescript 代码时:
npx ts-node src/server.ts
I receive the following error:我收到以下错误:
SyntaxError: Cannot use import statement outside a module
I followed the instructions suggested by the error:我按照错误提示的说明进行操作:
Warning: To load an ES module, set "type": "module" in the package.json or use the.mjs extension.
警告:要加载 ES 模块,请在 package.json 中设置“type”:“module”或使用 .mjs 扩展名。
But upon following these, I still had no luck and another error was thrown instead.但是在遵循这些之后,我仍然没有运气,而是抛出了另一个错误。
Here is the content of my server.ts file.这是我的 server.ts 文件的内容。
import App from './app';
const app = new App();
app.listen(3080);
tsconfig.json contents: 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"]
}
I'm not really sure what is causing this but would greatly appreciate some wisdom on the issue.我不确定是什么原因造成的,但非常感谢您在这个问题上的一些智慧。
Ideally i'd like to load the app via the server.ts file, while maintaining TypeScript contents.理想情况下,我想通过 server.ts 文件加载应用程序,同时维护 TypeScript 内容。
You may need "moduleResolution": "node"
in the compilerOptions
for ts to recognize these types of imports.您可能需要
compilerOptions
中的"moduleResolution": "node"
来让 ts 识别这些类型的导入。
Seth's answer was 100%.赛斯的回答是 100%。 Though turns out React was replacing the Typescript config with its own.
尽管事实证明 React 正在用自己的配置替换 Typescript 配置。 I've extended it and modified the extension to replace React's configuration.
我已经对其进行了扩展并修改了扩展以替换 React 的配置。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.