代码之家  ›  专栏  ›  技术社区  ›  Oliver Kucharzewski

使用ts节点编译nodejs代码时出现问题(无法在模块外使用import语句)

  •  0
  • Oliver Kucharzewski  · 技术社区  · 4 年前

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

    npx ts-node src/server.ts
    

    我收到以下错误:

    SyntaxError: Cannot use import statement outside a module
    

    我遵循了错误提示的说明:

    警告:要加载ES模块,请在中设置“类型”:“模块” 或使用.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内容。

    2 回复  |  直到 4 年前
        1
  •  2
  •   Seth Lutske    4 年前

    你可能需要 "moduleResolution": "node" compilerOptions 让ts识别这些类型的导入。

        2
  •  0
  •   Oliver Kucharzewski    4 年前

    赛斯的回答是100%。尽管事实证明React正在用自己的配置替换Typescript配置。我对它进行了扩展并修改了扩展以替换React的配置。

    推荐文章