|
import { isCSSRequest, preprocessCSS, resolveConfig, transformWithEsbuild } from 'vite'; |
|
import { mapToRelative, removeLangSuffix } from './utils/sourcemaps.js'; |
|
|
|
|
|
|
|
|
|
|
|
const supportedScriptLangs = ['ts']; |
|
|
|
export const lang_sep = '.vite-preprocess'; |
|
|
|
|
|
|
|
|
|
|
|
export function vitePreprocess(opts) { |
|
|
|
const preprocessor = { name: 'vite-preprocess' }; |
|
if (opts?.script !== false) { |
|
preprocessor.script = viteScript().script; |
|
} |
|
if (opts?.style !== false) { |
|
const styleOpts = typeof opts?.style == 'object' ? opts?.style : undefined; |
|
preprocessor.style = viteStyle(styleOpts).style; |
|
} |
|
return preprocessor; |
|
} |
|
|
|
|
|
|
|
|
|
function viteScript() { |
|
return { |
|
async script({ attributes, content, filename = '' }) { |
|
const lang = (attributes.lang); |
|
if (!supportedScriptLangs.includes(lang)) return; |
|
const { code, map } = await transformWithEsbuild(content, filename, { |
|
loader: (lang), |
|
target: 'esnext', |
|
tsconfigRaw: { |
|
compilerOptions: { |
|
|
|
importsNotUsedAsValues: 'preserve', |
|
preserveValueImports: true |
|
} |
|
} |
|
}); |
|
|
|
mapToRelative(map, filename); |
|
|
|
return { |
|
code, |
|
map |
|
}; |
|
} |
|
}; |
|
} |
|
|
|
|
|
|
|
|
|
|
|
function viteStyle(config = {}) { |
|
|
|
let cssTransform; |
|
|
|
const style = async ({ attributes, content, filename = '' }) => { |
|
const ext = attributes.lang ? `.${attributes.lang}` : '.css'; |
|
if (attributes.lang && !isCSSRequest(ext)) return; |
|
if (!cssTransform) { |
|
cssTransform = createCssTransform(style, config).then((t) => (cssTransform = t)); |
|
} |
|
const transform = await cssTransform; |
|
const suffix = `${lang_sep}${ext}`; |
|
const moduleId = `${filename}${suffix}`; |
|
const { code, map, deps } = await transform(content, moduleId); |
|
removeLangSuffix(map, suffix); |
|
mapToRelative(map, filename); |
|
const dependencies = deps ? Array.from(deps).filter((d) => !d.endsWith(suffix)) : undefined; |
|
return { |
|
code, |
|
map: map ?? undefined, |
|
dependencies |
|
}; |
|
}; |
|
|
|
style.__resolvedConfig = null; |
|
return { style }; |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
async function createCssTransform(style, config) { |
|
|
|
let resolvedConfig; |
|
|
|
if (style.__resolvedConfig) { |
|
|
|
resolvedConfig = style.__resolvedConfig; |
|
} else if (isResolvedConfig(config)) { |
|
resolvedConfig = config; |
|
} else { |
|
resolvedConfig = await resolveConfig( |
|
config, |
|
process.env.NODE_ENV === 'production' ? 'build' : 'serve' |
|
); |
|
} |
|
return async (code, filename) => { |
|
return preprocessCSS(code, filename, resolvedConfig); |
|
}; |
|
} |
|
|
|
|
|
|
|
|
|
|
|
function isResolvedConfig(config) { |
|
return !!config.inlineConfig; |
|
} |
|
|