fix(vite): Support fileReplacements for devServer (#13761)

Co-authored-by: ⁢ <john@doe.gov>
This commit is contained in:
nodegin 2022-12-13 19:11:29 +09:00 committed by GitHub
parent 9ac9491c3b
commit b3ff11f5d9
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -1,5 +1,6 @@
// source: https://github.com/Myrmod/vitejs-theming/blob/master/build-plugins/rollup/replace-files.js // source: https://github.com/Myrmod/vitejs-theming/blob/master/build-plugins/rollup/replace-files.js
import * as fs from 'fs';
import { resolve } from 'path'; import { resolve } from 'path';
/** /**
@ -14,11 +15,7 @@ export default function replaceFiles(replacements: FileReplacement[]) {
return { return {
name: 'rollup-plugin-replace-files', name: 'rollup-plugin-replace-files',
enforce: 'pre', enforce: 'pre',
async resolveId(source, importer, options) { async transform(code, id) {
const resolved = await this.resolve(source, importer, {
...options,
skipSelf: true,
});
/** /**
* The reason we're using endsWith here is because the resolved id * The reason we're using endsWith here is because the resolved id
* will be the absolute path to the file. We want to check if the * will be the absolute path to the file. We want to check if the
@ -27,7 +24,7 @@ export default function replaceFiles(replacements: FileReplacement[]) {
*/ */
const foundReplace = replacements.find((replacement) => const foundReplace = replacements.find((replacement) =>
resolved?.id?.endsWith(replacement.replace) id.endsWith(replacement.replace)
); );
if (foundReplace) { if (foundReplace) {
console.info( console.info(
@ -35,15 +32,15 @@ export default function replaceFiles(replacements: FileReplacement[]) {
); );
try { try {
// return new file content // return new file content
return { return fs
id: foundReplace.with, .readFileSync(id.replace(foundReplace.replace, foundReplace.with))
}; .toString();
} catch (err) { } catch (err) {
console.error(err); console.error(err);
return null; return code;
} }
} }
return null; return code;
}, },
}; };
} }