Skip to content

Instantly share code, notes, and snippets.

@otakustay
Created December 7, 2021 08:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save otakustay/b7b45aed2314ad2dfcfc59ca74c02493 to your computer and use it in GitHub Desktop.
Save otakustay/b7b45aed2314ad2dfcfc59ca74c02493 to your computer and use it in GitHub Desktop.
vite plugin style resources
import path from 'path';
import fs from 'fs/promises';
import {memoizeWith, always} from 'ramda';
import {Plugin} from 'vite';
const CSS_LANGS = new Set(['.less']);
export default function styleResourcePlugin(patterns: string[]): Plugin {
const readContent = memoizeWith(
always(''),
async () => {
const {globby} = await import('globby');
const files = await globby(patterns);
const contents = await Promise.all(files.map(v => fs.readFile(v, 'utf-8')));
return contents.join('\n\n');
}
);
return {
name: 'style-resource',
enforce: 'pre',
async transform(code, id) {
// 快速退出
if (!patterns.length) {
return;
}
const extension = path.extname(id);
if (CSS_LANGS.has(extension)) {
const prepend = await readContent();
return prepend + '\n\n' + code;
}
}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment