如果代码中使用 require 方式引入依赖,通常意味着代码是以 CommonJS 模块系统编写的,这是 Node.js 默认的模块系统。在这种情况下,parserOptions 中的 sourceType 应该配置为 "script",因为 require 是 CommonJS 特有的,而不是 ES6 模块的一部分。
示例配置
module.exports = {
parserOptions: {
ecmaVersion: 2021,
sourceType: 'script' // 适用于 CommonJS 模块
},
env: {
node: true // 确保全局变量如 `require` 可用
}
};
示例代码
当 sourceType 设置为 "script",并且环境配置为 Node.js 时,以下代码是有效的:
// example.js
const fs = require('fs'); // 使用 CommonJS 模块系统
function readFile(filePath) {
return fs.readFileSync(filePath, 'utf8');
}
module.exports = readFile;
配置解释
-
ecmaVersion:- 设置为
2021,确保解析最新的 ECMAScript 语法。
- 设置为
-
sourceType: 'script':- 指定代码被解析为普通脚本,而不是 ES6 模块。这样可以使用 CommonJS 模块系统(如
require和module.exports)。
- 指定代码被解析为普通脚本,而不是 ES6 模块。这样可以使用 CommonJS 模块系统(如
-
env: { node: true }:- 设置代码运行在 Node.js 环境,确保像
require、module、__dirname等全局变量可用。
- 设置代码运行在 Node.js 环境,确保像
补充说明
如果代码需要同时支持 CommonJS 和 ES6 模块,你可以使用 sourceType: 'module' 并在代码中混用 import 和 require,但需要注意,混用两种模块系统可能会引起问题,需要谨慎处理。一般情况下,在 Node.js 环境中,使用 CommonJS 模块系统更为常见和简洁。
总结
对于使用 require 方式引入依赖的代码,应将 sourceType 设置为 "script" 并配置 Node.js 环境。这将确保代码按照 CommonJS 模块系统进行解析和运行,适合传统的 Node.js 项目。
浙公网安备 33010602011771号