[Typescript] The module & moduleResolution Option in tsconfig.json

The module and moduleResolution options in the tsconfig.json file can be confusing.

Here we'll discuss the differences between the module and moduleResolution options and how to choose the right combination for your project.

Module and Module Resolution

The module setting in TypeScript specifies the kind of module code you want TypeScript to emit.

The moduleResolution option determines how TypeScript should resolve imports throughout your application.

There are several different options to choose from for both settings, but for practical purposes, you only need to consider two options for each setting:

If you're transpiling your code with TypeScript, you should choose module: NodeNext and moduleResolution: NodeNext.

If you're using another transpiler, you should choose module: ESNext and moduleResolution: Bundler.

The NodeNext Setting

When setting module and moduleResolution both to "NodeNext", TypeScript will want you to add a .js extension to local file imports.

// inside tsconfig.json
"compilerOptions": {
  "module": "NodeNext",
  "moduleResolution": "NodeNext"
...

This might seem strange as you're importing a .ts file, but it's because TypeScript targets the compiled JavaScript file, not the TypeScript source file. TypeScript never wants to change runtime behavior by altering import paths, hence the need for a .js extension.

This setting combination is useful when working on the backend with Node.js.

The ESNext and Bundler Settings

If you want to import without specifying an extension, you can use module: "ESNext" and moduleResolution: "Bundler":

// inside tsconfig.json
"compilerOptions": {
  "module": "ESNext",
  "moduleResolution": "Bundler"
  ...

This configuration is more flexible with extensions and is handled by the bundler.

In general, if you're working on the front-end with a framework like Vite or Next.js, you'll likely want moduleResolution: Bundler.

The Big Takeaway

Remember, if you're transpiling your code yourself, go with module: NodeNext and moduleResolution: NodeNext. If another bundler is handling it, you'll need module: ESNext and moduleResolution: Bundler.

posted @ 2024-08-13 01:17  Zhentiw  阅读(15)  评论(0编辑  收藏  举报