UNPKG

vite-plugin-eslint2

Version:
87 lines (84 loc) 2.78 kB
import { dirname, extname, resolve } from 'node:path'; import { fileURLToPath } from 'node:url'; import { Worker } from 'node:worker_threads'; import debugWrap from 'debug'; import { P as PLUGIN_NAME, g as getOptions, a as getFilter, i as initializeESLint, l as lintFiles, s as shouldIgnoreModule, b as getFilePath } from './shared/vite-plugin-eslint2.B7EWfSXj.mjs'; import '@rollup/pluginutils'; const debug = debugWrap(PLUGIN_NAME); const __filename = fileURLToPath(import.meta.url); const __dirname = dirname(__filename); const ext = extname(__filename); function ESLintPlugin(userOptions = {}) { const options = getOptions(userOptions); let worker; const filter = getFilter(options); let eslintInstance; let formatter; let outputFixes; return { name: PLUGIN_NAME, apply(config, { command }) { debug("==== apply hook ===="); if (config.mode === "test" || process.env.VITEST) return options.test; const shouldApply = command === "serve" && options.dev || command === "build" && options.build; debug(`should apply this plugin: ${shouldApply}`); return shouldApply; }, async buildStart() { debug("==== buildStart hook ===="); if (options.lintInWorker) { if (worker) return; debug("Initialize worker"); worker = new Worker(resolve(__dirname, `worker${ext}`), { workerData: { options } }); return; } debug("Initial ESLint"); const result = await initializeESLint(options); eslintInstance = result.eslintInstance; formatter = result.formatter; outputFixes = result.outputFixes; if (options.lintOnStart) { debug("Lint on start"); await lintFiles( { files: options.include, eslintInstance, formatter, outputFixes, options }, this // use buildStart hook context ); } }, async transform(_, id) { debug("==== transform hook ===="); if (worker) return worker.postMessage(id); debug(`id: ${id}`); const shouldIgnore = await shouldIgnoreModule(id, filter, eslintInstance); debug(`should ignore: ${shouldIgnore}`); if (shouldIgnore) return; const filePath = getFilePath(id); debug(`filePath: ${filePath}`); return await lintFiles( { files: options.lintDirtyOnly ? filePath : options.include, eslintInstance, formatter, outputFixes, options }, this // use transform hook context ); }, async buildEnd() { debug("==== buildEnd hook ===="); if (worker) await worker.terminate(); } }; } export { ESLintPlugin as default };