Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(vite): Support fileReplacements for devServer #13761

Merged
merged 3 commits into from
Dec 13, 2022
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 6 additions & 11 deletions packages/vite/plugins/rollup-replace-files.plugin.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
// source: https://github.com/Myrmod/vitejs-theming/blob/master/build-plugins/rollup/replace-files.js

import fs from 'fs';
nodegin marked this conversation as resolved.
Show resolved Hide resolved
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,21 @@ 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