简体   繁体   English

如何将 Typescript 编译为使用 ES6 模块的 JS?

[英]How to compile Typescript to JS that uses ES6 modules?

My tsconfig.json file contains我的tsconfig.json文件包含

{
    "compilerOptions": {
        "module": "esnext",
        "target": "esnext",
    }
}

But the compiled JS files still use exports / require syntax.但是编译后的 JS 文件仍然使用exports / require语法。

How do I fix this?我该如何解决?

EDIT:编辑:

My directory structure is as follows我的目录结构如下

- APIs/
  - emails/
    - sendEmail.ts
  - oldFiles/
    - file1.js
    - file2.js
- index.js
- tsconfig.json
- package.json

I am running tsc using the command tsc APIs/emails/sendEmail.ts from the root directory.我正在使用根目录中的命令tsc APIs/emails/sendEmail.ts运行tsc

Those settings are correct, so most likely you're not actually using that tsconfig.json file.这些设置是正确的,因此很可能您实际上并未使用该tsconfig.json文件。 For instance, if you do tsc someFile.ts , tsc doesn't use the tsconfig.json (surprisingly).例如,如果您执行tsc someFile.ts ,则tsc不使用tsconfig.json (令人惊讶)。 Your best bet is probably to add an includes to your configuration (so tsc knows what it's compiling) and then compile simply by invoking tsc , which will look for a local tsconfig.json .您最好的选择可能是在您的配置中添加一个includes (以便tsc知道它正在编译什么),然后通过调用tsc进行编译,这查找本地tsconfig.json

{
    "compilerOptions": {
        "module": "esnext",
        "target": "esnext"
    },
    "include": ["**/*.ts"]
}

Then in package.json (for instance):然后在package.json中(例如):

// ...
"scripts": {
    "build": "tsc"
}
// ...

This config should work.这个配置应该可以工作。 But it's tsconfig.json not tsconfig.js .但它是tsconfig.json而不是tsconfig.js

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM