Skip to content

Commit

Permalink
fix(vite): Support fileReplacements for devServer (#13761)
Browse files Browse the repository at this point in the history
Co-authored-by: ⁢ <john@doe.gov>
(cherry picked from commit b3ff11f)
  • Loading branch information
nodegin authored and FrozenPandaz committed Dec 19, 2022
1 parent b5860f6 commit 7fa9161
Showing 1 changed file with 8 additions and 11 deletions.
19 changes: 8 additions & 11 deletions packages/vite/plugins/rollup-replace-files.plugin.ts
@@ -1,5 +1,6 @@
// source: https://github.com/Myrmod/vitejs-theming/blob/master/build-plugins/rollup/replace-files.js

import * as fs from 'fs';
import { resolve } from 'path';

/**
Expand All @@ -14,11 +15,7 @@ export default function replaceFiles(replacements: FileReplacement[]) {
return {
name: 'rollup-plugin-replace-files',
enforce: 'pre',
async resolveId(source, importer, options) {
const resolved = await this.resolve(source, importer, {
...options,
skipSelf: true,
});
async transform(code, 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
Expand All @@ -27,23 +24,23 @@ export default function replaceFiles(replacements: FileReplacement[]) {
*/

const foundReplace = replacements.find((replacement) =>
resolved?.id?.endsWith(replacement.replace)
id.endsWith(replacement.replace)
);
if (foundReplace) {
console.info(
`replace "${foundReplace.replace}" with "${foundReplace.with}"`
);
try {
// return new file content
return {
id: foundReplace.with,
};
return fs
.readFileSync(id.replace(foundReplace.replace, foundReplace.with))
.toString();
} catch (err) {
console.error(err);
return null;
return code;
}
}
return null;
return code;
},
};
}
Expand Down

0 comments on commit 7fa9161

Please sign in to comment.