制作“导入/扩展”需要Node.js打字稿项目中的.js扩展
首先,一些事实:
- node.js要求所有local
import
s包括导入模块的扩展(例如'./hello.js',而不是<<代码>从'./hello'导入Hello)。 - TypeScript将在有或没有
.js
扩展程序的情况下编译导入
s,这意味着缺少.js
扩展名是运行时错误。 - Typescript不会转换
导入
s以添加.js
扩展名或转换.ts
to.js
。
在我的node.js项目中,我想使用 import/Extensions
eslint规则,让缺少丢失的 .js
扩展名为构建时间错误。但是,当我使用以下配置启用此规则时:
{
"root": true,
"env": {
"node": true
},
"parser": "@typescript-eslint/parser",
"plugins": [
"@typescript-eslint"
],
"extends": [
"eslint:recommended",
"plugin:import/recommended",
"plugin:import/typescript",
"plugin:@typescript-eslint/eslint-recommended",
"plugin:@typescript-eslint/recommended"
],
"settings": {
"import/resolver": {
"typescript": {},
"node": {
"extensions": [".js"]
}
}
},
"rules": {
"import/extensions": ["error", "ignorePackages"]
}
}
运行 ESLINT
给出了以下错误:
/sandbox/src/index.ts
1:19 error Missing file extension "ts" for "./hello.js" import/extensions
源文件:
// index.ts
import hello from "./hello.js";
hello();
// hello.ts
export default function hello() {
console.log("Hello");
}
codesandbox链接: https://codesandbox.io/s/elated-germain-13glp7
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我用以下配置修复了此问题:
主要的是禁用
“导入/否分辨”
规则,然后删除“设置”。“ import/import/resolver”。“ node” 。 (
“导入/未解决”
是多余的/代码>插件。I fixed this with the following config:
The main thing is to disable the
"import/no-unresolved"
rule and remove"settings"."import/resolver"."node"
. ("import/no-unresolved"
is redundant as unresolved imports are resolved at the compilation stage.) Other items removed here were already being added as a result of extending the@typescript-eslint
plugins.我找到了一个ESLINT插件,可以修复
.ts
文件中的导入的.js
扩展,而不仅仅是显示错误:https://github.com/AlexSergey/eslint-plugin-file-extension-in-import-ts< /a>
install:
添加到
.eslintrc
file:注意:我遇到了类似于 https://github.com/import-js/emport-js/eslint-plugin-import/- essugy/1292 使用此软件包时,它将错误地尝试在自动修复时在这些路径上添加
.js
扩展。I found an eslint plugin that can fix missing
.js
extensions for imports in.ts
files, instead of just showing an error:https://github.com/AlexSergey/eslint-plugin-file-extension-in-import-ts
https://www.npmjs.com/package/eslint-plugin-file-extension-in-import-ts
Install:
Add to
.eslintrc
file:NOTE: I ran into an issue similar to https://github.com/import-js/eslint-plugin-import/issues/1292 when using this package, and it will incorrectly try to add
.js
extensions on these paths when fixing automatically.您可以尝试
ts-add-js-extension
软件包,以附加.js
扩展到thrabiled的JavaScript文件。安装后,您可以做You could try
ts-add-js-extension
package to append.js
extension to the transpiled JavaScript files. After you install you can do