David Callanan
David Callanan

Reputation: 5968

TypeScript import with extension

You may have heard of Deno which is a new TypeScript runtime.

One major difference between Deno and normal TypeScript is that you must include the file extension in the import statement. e.g:

import foo from './bar.ts'
                       ^^

I would like to write code that is compatible with both Deno and Webpack.

How can I configure Webpack to allow importing with .ts extension like above?

Also, how can I prevent the following VSCode error?

enter image description here

Upvotes: 5

Views: 3806

Answers (1)

Matthias Fischer
Matthias Fischer

Reputation: 1006

Webpack can be configured to resolve the extensions of all imports with the resolve property. If there is an empty string within the list of extensions webpack will accept imports with full extension as well. The empty string should be the first entry in the list.

module.exports = {
 // ...
 resolve: {
   extensions: ['', '.ts', '.tsx' /*etc ...*/],
 }
}

If there is no empty string in the list of extensions to use webpack will try to import something like ./bar.ts.ts instead of ./bar.ts.

You can disable warnings in VSCode from the ts-compiler using a comment like

// @ts-ignore TS6133
import foo from './bar.ts'

Upvotes: 4

Related Questions