Created
December 7, 2021 08:53
-
-
Save otakustay/b7b45aed2314ad2dfcfc59ca74c02493 to your computer and use it in GitHub Desktop.
vite plugin style resources
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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