Skip to content

Commit dad36f2

Browse files
authored
fix: adjust renderBuiltUrl resolution for relative pathing (#393)
1 parent 1953b43 commit dad36f2

File tree

1 file changed

+42
-8
lines changed

1 file changed

+42
-8
lines changed

src/plugins/pluginAddEntry.ts

Lines changed: 42 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -135,21 +135,55 @@ const addEntry = ({
135135
generateBundle(options, bundle) {
136136
if (!injectHtml()) return;
137137
const file = this.getFileName(emitFileId);
138-
const path = viteConfig.experimental?.renderBuiltUrl
139-
? viteConfig.experimental?.renderBuiltUrl(file)
140-
: viteConfig.base + file;
141-
const scriptContent = `
142-
<script type="module" src="${path}"></script>
143-
`;
138+
// Helper to resolve path with proper renderBuiltUrl handling
139+
const resolvePath = (htmlFileName: string): string => {
140+
if (!viteConfig.experimental?.renderBuiltUrl) {
141+
return viteConfig.base + file;
142+
}
143+
144+
const result = viteConfig.experimental.renderBuiltUrl(file, {
145+
hostId: htmlFileName,
146+
hostType: 'html',
147+
type: 'asset',
148+
ssr: false,
149+
});
150+
151+
// Handle return types
152+
if (typeof result === 'string') {
153+
return result;
154+
}
155+
156+
if (result && typeof result === 'object') {
157+
if ('runtime' in result) {
158+
// Runtime code cannot be used in <script src="">
159+
console.warn(
160+
'[vite-plugin-federation] renderBuiltUrl returned runtime code for HTML injection. ' +
161+
'Runtime code cannot be used in <script src="">. Falling back to base path.'
162+
);
163+
return viteConfig.base + file;
164+
}
165+
if (result.relative) {
166+
return file;
167+
}
168+
}
144169

170+
// Fallback for undefined or unexpected values
171+
return viteConfig.base + file;
172+
};
173+
174+
// Process each HTML file
145175
for (const fileName in bundle) {
146176
if (fileName.endsWith('.html')) {
147177
let htmlAsset = bundle[fileName];
148178
if (htmlAsset.type === 'chunk') return;
149-
let htmlContent = htmlAsset.source.toString() || '';
150179

151-
htmlContent = htmlContent.replace('<head>', `<head>${scriptContent}`);
180+
const path = resolvePath(fileName);
181+
const scriptContent = `
182+
<script type="module" src="${path}"></script>
183+
`;
152184

185+
let htmlContent = htmlAsset.source.toString() || '';
186+
htmlContent = htmlContent.replace('<head>', `<head>${scriptContent}`);
153187
htmlAsset.source = htmlContent;
154188
}
155189
}

0 commit comments

Comments
 (0)