UNPKG

vite-plugin-stylelint

Version:
81 lines (79 loc) 2.58 kB
import { PLUGIN_NAME, getFilePath, getFilter, getOptions, initializeStylelint, lintFiles, shouldIgnoreModule } from "./utils-C5rXlwKu.js"; import { dirname, extname, resolve } from "node:path"; import { fileURLToPath } from "node:url"; import { Worker } from "node:worker_threads"; import debugWrap from "debug"; //#region src/index.ts const debug = debugWrap(PLUGIN_NAME); const __filename = fileURLToPath(import.meta.url); const __dirname = dirname(__filename); const ext = extname(__filename); function StylelintPlugin(userOptions = {}) { const options = getOptions(userOptions); let worker; const filter = getFilter(options); let stylelintInstance; let formatter; 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 Stylelint"); const result = await initializeStylelint(options); stylelintInstance = result.stylelintInstance; formatter = result.formatter; if (options.lintOnStart) { debug("Lint on start"); await lintFiles({ files: options.include, stylelintInstance, formatter, options }, this); } }, async transform(_, id) { debug("==== transform hook ===="); debug(`id: ${id}`); const watchIds = this.getWatchFiles(); debug(`watchIds: ${watchIds}`); const ids = [id, ...watchIds]; debug(`ids: ${ids}`); if (worker) { for (const id$1 of ids) worker.postMessage(id$1); return; } const filteredIds = ids.filter((id$1) => !shouldIgnoreModule(id$1, filter)); debug(`filteredIds: ${filteredIds}`); const shouldIgnore = filteredIds.length === 0; debug(`should ignore: ${shouldIgnore}`); if (shouldIgnore) return; const filePaths = filteredIds.map((id$1) => getFilePath(id$1)); return await lintFiles({ files: options.lintDirtyOnly ? filePaths : options.include, stylelintInstance, formatter, options }, this); }, async buildEnd() { debug("==== buildEnd hook ===="); if (worker) await worker.terminate(); } }; } //#endregion export { StylelintPlugin as default };