带扩展名的 TypeScript 导入 [英] TypeScript import with extension

查看:66
本文介绍了带扩展名的 TypeScript 导入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您可能听说过 Deno,它是一个新的 TypeScript 运行时.

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

Deno 和普通 TypeScript 的一个主要区别是你必须在 import 语句中包含文件扩展名.例如:

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'
                       ^^

我想编写兼容 Deno 和 Webpack 的代码.

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

如何配置 Webpack 以允许使用上述 .ts 扩展名导入?

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

另外,如何防止以下 VSCode 错误?

Also, how can I prevent the following VSCode error?

推荐答案

Webpack 可以配置为使用 resolve 属性解析所有导入的扩展名.如果扩展列表中有一个空字符串,webpack 也将接受带有完整扩展的导入.空字符串应该是列表中的第一个条目.

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 ...*/],
 }
}

如果要使用的扩展列表中没有空字符串,webpack 将尝试导入类似 ./bar.ts.ts 的内容而不是 ./bar.ts.

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.

您可以在 ts-compiler 中使用类似注释禁用 VSCode 中的警告

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

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

这篇关于带扩展名的 TypeScript 导入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆