这个错误信息是由 ESLint 插件 @typescript-eslint/no-var-requires
触发的,它提示你在 TypeScript 代码中使用了 require
语句,而不是推荐的 import
语句。这个规则的目的是鼓励使用 ES6 模块语法,因为它提供了更好的静态分析和树摇(tree shaking)能力。
import
和 export
关键字的模块系统。require
和 module.exports
的模块系统,常见于 Node.js 环境。import
允许编译器在编译时进行更好的优化和错误检查。import
语法来移除未使用的代码,减少最终包的大小。import()
可以用于动态导入模块,支持代码分割。import { something } from 'module';
import something from 'module';
import * as module from 'module';
import { originalName as newName } from 'module';
如果你遇到这个错误,可以通过以下几种方式来解决:
import
替换 require
// 错误示例
const express = require('express');
// 正确示例
import express from 'express';
require
,可以关闭这条规则在你的 .eslintrc
或相应的配置文件中添加以下配置:
{
"rules": {
"@typescript-eslint/no-var-requires": "off"
}
}
import()
// 动态导入模块
const modulePath = './path/to/module';
import(modulePath).then((module) => {
// 使用模块
});
假设你有一个 TypeScript 文件 app.ts
,原本使用 require
:
const express = require('express');
const app = express();
app.get('/', (req, res) => {
res.send('Hello World!');
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
修改为使用 import
:
import express from 'express';
const app = express();
app.get('/', (req, res) => {
res.send('Hello World!');
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
这样就可以避免 ESLint 报错,并且利用了 ES6 模块的优势。
领取专属 10元无门槛券
手把手带您无忧上云