ESLint源码分析(2) ignore

334 阅读1分钟

eslintignore的配置机制

对于eslintrc而言,可以在多个文件夹中进行配置,按照层级去继承属性,这在文档中有明确的说明:Using Configuration Files。但对于.eslintignore文件而言,按照文档中的说明,是只能在根目录创建的,根目录就是指process.cwd()指定的目录,和package.json在同一个目录下。加载.eslintignore的源码在此处 loadDefaultESLintIgnore

    loadDefaultESLintIgnore() {
        const slots = internalSlotsMap.get(this);
        const eslintIgnorePath = path.resolve(slots.cwd, ".eslintignore");
        const packageJsonPath = path.resolve(slots.cwd, "package.json");

        if (fs.existsSync(eslintIgnorePath)) {
            return this.loadESLintIgnore(eslintIgnorePath);
        }
        if (fs.existsSync(packageJsonPath)) {
            const data = loadJSONConfigFile(packageJsonPath);

            if (Object.hasOwnProperty.call(data, "eslintIgnore")) {
                if (!Array.isArray(data.eslintIgnore)) {
                    throw new Error("Package.json eslintIgnore property requires an array of paths");
                }
                const ctx = createContext(
                    slots,
                    "ignore",
                    "eslintIgnore in package.json",
                    packageJsonPath,
                    slots.cwd
                );

                return new ConfigArray(
                    ...this._normalizeESLintIgnoreData(data.eslintIgnore, ctx)
                );
            }
        }

        return new ConfigArray();
    }

可见在使用.eslintignore的次序上,是先使用.eslintignore文件,其次是package.json文件中的eslintIgnore字段。

由于对于根目录的定义比较模糊,所以会遇到使用vscode-eslint插件的时候,会发现.eslintignore文件必须放在项目的最上层目录才可以。在package.json不在最上层目录的时候,可能vscodeignore机制和执行npm eslint命令体现的ignore机制会不一致,加载ignore文件的路径不同