Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript import with extension

Tags:

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

like image 796
David Callanan Avatar asked May 18 '19 13:05

David Callanan


People also ask

How do I import files into TypeScript?

To import a class from another file in TypeScript: Export the class from file A , e.g. export class Employee {} . Import the class in file B as import { Employee } from './another-file' . Use the class in file B .

What is the extension for TypeScript?

ts file is used to provide TypeScript type information about an API that's written in JavaScript.

Does TypeScript use import?

Importing TypesWith TypeScript 3.8, you can import a type using the import statement, or using import type .


1 Answers

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'
like image 125
Matthias Fischer Avatar answered Nov 07 '22 04:11

Matthias Fischer