【问题标题】:Issues compiling nodejs code with ts-node (Cannot use import statement outside a module)使用 ts-node 编译 nodejs 代码时出现问题(不能在模块外使用 import 语句)
【发布时间】:2021-12-31 16:22:05
【问题描述】:

当尝试使用以下命令使用 NodeJS 编译 typescript 代码时:

npx ts-node src/server.ts

我收到以下错误:

SyntaxError: Cannot use import statement outside a module

我按照错误提示的说明进行操作:

警告:要加载 ES 模块,请在 package.json 或使用 .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 内容。

【问题讨论】:

    标签: node.js typescript express


    【解决方案1】:

    您可能需要 compilerOptions 中的 "moduleResolution": "node" 以便 ts 识别这些类型的导入。

    【讨论】:

      猜你喜欢
      • 2020-12-31
      • 2022-06-24
      • 1970-01-01
      • 1970-01-01
      • 2020-02-09
      • 2020-01-27
      • 2020-02-11
      • 2020-12-11
      相关资源
      最近更新 更多