首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >编译带有ts-节点的nodejs代码的问题(不能在模块外使用导入语句)

编译带有ts-节点的nodejs代码的问题(不能在模块外使用导入语句)
EN

Stack Overflow用户
提问于 2021-11-21 23:33:44
回答 1查看 86关注 0票数 0

当试图使用NodeJS编译类型记录代码时,请使用以下命令:

代码语言:javascript
运行
复制
npx ts-node src/server.ts

我收到以下错误:

代码语言:javascript
运行
复制
SyntaxError: Cannot use import statement outside a module

我遵循了错误提示的指示:

警告:要加载ES模块,请在package.json中设置"type":“.mjs”或使用.mjs扩展。

但经过这些之后,我仍然没有运气,另一个错误被抛出。

这是我的server.ts文件的内容。

代码语言:javascript
运行
复制
import App from './app';
const app = new App();
app.listen(3080);

tsconfig.json内容:

代码语言:javascript
运行
复制
{
  "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内容。

EN

Stack Overflow用户

回答已采纳

发布于 2021-11-21 23:50:21

您可能需要在"moduleResolution": "node"中使用compilerOptions来识别这些类型的导入。

票数 2
EN
查看全部 1 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70059474

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档