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(rspack): support getPublicPath #3422

Open
wants to merge 8 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
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
5 changes: 5 additions & 0 deletions .changeset/shiny-geckos-switch.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@module-federation/rspack': patch
---

fix(rspack): support getPublicPath
2 changes: 0 additions & 2 deletions apps/router-demo/router-host-vue3-2100/rsbuild.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,6 @@ export default defineConfig({
port: 2100,
},
dev: {
// It is necessary to configure assetPrefix, and in the production environment, you need to configure output.assetPrefix
assetPrefix: 'http://localhost:2100',
writeToDisk: true,
},
plugins: [
Expand Down
7 changes: 0 additions & 7 deletions apps/router-demo/router-remote1-2001/rsbuild.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,15 +20,8 @@ export default defineConfig({
port: 2001,
},
dev: {
// It is necessary to configure assetPrefix, and in the production environment, you need to configure output.assetPrefix
assetPrefix: 'http://localhost:2001',
writeToDisk: true,
},
tools: {
rspack: (config, { appendPlugins }) => {
delete config.optimization?.splitChunks;
},
},
plugins: [
pluginReact(),
pluginModuleFederation({
Expand Down
22 changes: 0 additions & 22 deletions apps/router-demo/router-remote2-2002/rsbuild.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,28 +17,6 @@ export default defineConfig({
server: {
port: 2002,
},
dev: {
// It is necessary to configure assetPrefix, and in the production environment, you need to configure output.assetPrefix
assetPrefix: 'http://localhost:2002',
},
tools: {
// cssExtract: {
// pluginOptions: {
// insert(element) {
// console.log('element22222233333333333333',document.querySelector("#remote2-style-component"));
// document.querySelector("#remote2-style-component")?.appendChild(element);
// },
// }
// },
// styleLoader: {
// insert: (element)=> {
// debugger
// const styleContainer = document.querySelector(".remote2_export-app") || document.head;
// styleContainer.appendChild(element);
// console.log('styleContainer', styleContainer)
// },
// },
},
plugins: [
pluginReact(),
pluginModuleFederation({
Expand Down
9 changes: 1 addition & 8 deletions apps/router-demo/router-remote3-2003/rsbuild.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,16 +13,8 @@ export default defineConfig({
port: 2003,
},
dev: {
// It is necessary to configure assetPrefix, and in the production environment, you need to configure output.assetPrefix
assetPrefix: 'http://localhost:2003',
writeToDisk: true,
},
tools: {
rspack: (config, { appendPlugins }) => {
delete config.optimization?.splitChunks;
},
},

plugins: [
pluginVue(),
pluginModuleFederation({
Expand All @@ -31,6 +23,7 @@ export default defineConfig({
'./export-app': './src/export-app.ts',
},
shared: ['vue', 'vue-router'],
getPublicPath: `return 'http://localhost:2003/'`,
}),
],
});
30 changes: 5 additions & 25 deletions apps/router-demo/router-remote4-2004/rsbuild.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,33 +14,11 @@ export default defineConfig({
'react-dom': path.resolve(__dirname, 'node_modules/react-dom'),
},
},
server: {
port: 2004,
},
dev: {
// It is necessary to configure assetPrefix, and in the production environment, you need to configure output.assetPrefix
assetPrefix: 'http://localhost:2004',
writeToDisk: true,
},
tools: {
rspack: (config, { appendPlugins }) => {
delete config.optimization?.splitChunks;
},
// cssExtract: {
// pluginOptions: {
// insert(element) {
// console.log('element22222233333333333333',document.querySelector("#remote2-style-component"));
// document.querySelector("#remote2-style-component")?.appendChild(element);
// },
// }
// },
// styleLoader: {
// insert: (element)=> {
// debugger
// const styleContainer = document.querySelector(".remote2_export-app") || document.head;
// styleContainer.appendChild(element);
// console.log('styleContainer', styleContainer)
// },
// },
server: {
port: 2004,
},
plugins: [
pluginReact(),
Expand All @@ -50,6 +28,8 @@ export default defineConfig({
'./export-app': './src/export-App.tsx',
},
shared: ['react', 'react-dom'],
// getPublicPath: `return 'http://localhost:2004/'`,
getPublicPath: `function(originalPublicPath){console.log(originalPublicPath);__webpack_require__.p = 'http://localhost:2004/'}`,
}),
],
});
1 change: 0 additions & 1 deletion packages/data-prefetch/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
"skipLibCheck": true,
"moduleResolution": "node",
"allowJs": false,
"strict": true,
"types": ["jest", "node"],
"experimentalDecorators": true,
"resolveJsonModule": true,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ import SharePlugin from '../sharing/SharePlugin';
import ContainerPlugin from './ContainerPlugin';
import ContainerReferencePlugin from './ContainerReferencePlugin';
import FederationRuntimePlugin from './runtime/FederationRuntimePlugin';
import { RemoteEntryPlugin } from './runtime/RemoteEntryPlugin';
import { RemoteEntryPlugin } from '@module-federation/rspack/remote-entry-plugin';
import { ExternalsType } from 'webpack/declarations/WebpackOptions';
import StartupChunkDependenciesPlugin from '../startup/MfStartupChunkDependenciesPlugin';
import FederationModulesPlugin from './runtime/FederationModulesPlugin';
Expand Down Expand Up @@ -69,6 +69,7 @@ class ModuleFederationPlugin implements WebpackPluginInstance {
// must before ModuleFederationPlugin
if (options.getPublicPath && options.name) {
new RemoteEntryPlugin(options.name, options.getPublicPath).apply(
// @ts-ignore
compiler,
);
}
Expand Down
9 changes: 9 additions & 0 deletions packages/rspack/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
"module": "./dist/index.esm.mjs",
"types": "./dist/index.cjs.d.ts",
"dependencies": {
"btoa": "1.2.1",
"@module-federation/bridge-react-webpack-plugin": "workspace:*",
"@module-federation/dts-plugin": "workspace:*",
"@module-federation/managers": "workspace:*",
Expand All @@ -45,6 +46,11 @@
"types": "./dist/plugin.cjs.d.ts",
"import": "./dist/plugin.esm.mjs",
"require": "./dist/plugin.cjs.js"
},
"./remote-entry-plugin": {
"types": "./dist/remote-entry-plugin.cjs.d.ts",
"import": "./dist/remote-entry-plugin.esm.mjs",
"require": "./dist/remote-entry-plugin.cjs.js"
}
},
"typesVersions": {
Expand All @@ -54,6 +60,9 @@
],
"plugin": [
"./dist/plugin.cjs.d.ts"
],
"remote-entry-plugin": [
"./dist/remote-entry-plugin.cjs.d.ts"
]
}
},
Expand Down
4 changes: 4 additions & 0 deletions packages/rspack/rollup.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,10 @@ module.exports = (rollupConfig, projectOptions) => {
process.cwd(),
'./packages/rspack/src/ModuleFederationPlugin.ts',
);
rollupConfig.input['remote-entry-plugin'] = path.resolve(
process.cwd(),
'./packages/rspack/src/RemoteEntryPlugin.ts',
);

if (Array.isArray(rollupConfig.output)) {
rollupConfig.output = rollupConfig.output.map((c) => ({
Expand Down
8 changes: 8 additions & 0 deletions packages/rspack/src/ModuleFederationPlugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import { DtsPlugin } from '@module-federation/dts-plugin';
import ReactBridgePlugin from '@module-federation/bridge-react-webpack-plugin';
import path from 'node:path';
import fs from 'node:fs';
import { RemoteEntryPlugin } from './RemoteEntryPlugin';

type ExcludeFalse<T> = T extends undefined | false ? never : T;
type SplitChunks = Compiler['options']['optimization']['splitChunks'];
Expand Down Expand Up @@ -75,6 +76,13 @@ export class ModuleFederationPlugin implements RspackPluginInstance {
this._patchChunkSplit(compiler, options.name);
}

// must before ModuleFederationPlugin
if (options.getPublicPath && options.name) {
new RemoteEntryPlugin(options.name, options.getPublicPath).apply(
compiler,
);
}

if (options.experiments?.provideExternalRuntime) {
if (options.exposes) {
throw new Error(
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,27 @@
import type { Compiler, WebpackPluginInstance } from 'webpack';
import type { Compiler, RspackPluginInstance } from '@rspack/core';
// @ts-ignore
import pBtoa from 'btoa';

export class RemoteEntryPlugin implements WebpackPluginInstance {
const charMap: Record<string, string> = {
'<': '\\u003C',
'>': '\\u003E',
'/': '\\u002F',
'\\': '\\\\',
'\b': '\\b',
'\f': '\\f',
'\n': '\\n',
'\r': '\\r',
'\t': '\\t',
'\0': '\\0',
'\u2028': '\\u2028',
'\u2029': '\\u2029',
};

function escapeUnsafeChars(str: string) {
return str.replace(/[<>\b\f\n\r\t\0\u2028\u2029\\]/g, (x) => charMap[x]);
}

export class RemoteEntryPlugin implements RspackPluginInstance {
readonly name = 'VmokRemoteEntryPlugin';
private _name: string;
private _getPublicPath: string;
Expand All @@ -13,12 +33,14 @@

apply(compiler: Compiler): void {
let code;
const sanitizedPublicPath = escapeUnsafeChars(this._getPublicPath);

if (!this._getPublicPath.startsWith('function')) {
code = `${
compiler.webpack.RuntimeGlobals.publicPath
} = new Function(${JSON.stringify(this._getPublicPath)})()`;
} = new Function(${JSON.stringify(sanitizedPublicPath)})()`;
Fixed Show fixed Hide fixed
Fixed Show fixed Hide fixed

Check warning

Code scanning / CodeQL

Improper code sanitization Medium

Code construction depends on an
improperly sanitized value
.

Copilot Autofix AI 13 days ago

To fix the problem, we need to ensure that the sanitizedPublicPath value is properly sanitized to prevent any potential code injection. We can achieve this by using a more robust sanitization method that escapes all potentially dangerous characters. Additionally, we should ensure that the JSON.stringify method is used correctly to handle the sanitized value.

  • Update the escapeUnsafeChars function to include all potentially dangerous characters.
  • Ensure that the sanitizedPublicPath value is properly escaped before using it in the JSON.stringify method.
Suggested changeset 1
packages/rspack/src/RemoteEntryPlugin.ts

Autofix patch

Autofix patch
Run the following command in your local git repository to apply this patch
cat << 'EOF' | git apply
diff --git a/packages/rspack/src/RemoteEntryPlugin.ts b/packages/rspack/src/RemoteEntryPlugin.ts
--- a/packages/rspack/src/RemoteEntryPlugin.ts
+++ b/packages/rspack/src/RemoteEntryPlugin.ts
@@ -20,3 +20,3 @@
 function escapeUnsafeChars(str: string) {
-  return str.replace(/[<>\b\f\n\r\t\0\u2028\u2029\\]/g, (x) => charMap[x]);
+  return str.replace(/[<>\b\f\n\r\t\0\u2028\u2029/\\]/g, (x) => charMap[x]);
 }
@@ -40,3 +40,3 @@
         compiler.webpack.RuntimeGlobals.publicPath
-      } = new Function(${JSON.stringify(sanitizedPublicPath)})()`;
+      } = new Function(${JSON.stringify(escapeUnsafeChars(sanitizedPublicPath))})()`;
     } else {
EOF
@@ -20,3 +20,3 @@
function escapeUnsafeChars(str: string) {
return str.replace(/[<>\b\f\n\r\t\0\u2028\u2029\\]/g, (x) => charMap[x]);
return str.replace(/[<>\b\f\n\r\t\0\u2028\u2029/\\]/g, (x) => charMap[x]);
}
@@ -40,3 +40,3 @@
compiler.webpack.RuntimeGlobals.publicPath
} = new Function(${JSON.stringify(sanitizedPublicPath)})()`;
} = new Function(${JSON.stringify(escapeUnsafeChars(sanitizedPublicPath))})()`;
} else {
Copilot is powered by AI and may make mistakes. Always verify output.
Positive Feedback
Negative Feedback

Provide additional feedback

Please help us improve GitHub Copilot by sharing more details about this comment.

Please select one or more of the options
} else {
code = `(${this._getPublicPath})()`;
code = `(${sanitizedPublicPath}(${compiler.webpack.RuntimeGlobals.publicPath}))`;
}
const base64Code = pBtoa(code);
const dataUrl = `data:text/javascript;base64,${base64Code}`;
Expand Down
1 change: 0 additions & 1 deletion packages/rspack/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
"compilerOptions": {
"module": "commonjs",
"forceConsistentCasingInFileNames": true,
"strict": true,
"noImplicitOverride": true,
"noPropertyAccessFromIndexSignature": true,
"noImplicitReturns": true,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,6 @@
"tsConfig": "packages/runtime-plugins/inject-external-runtime-core-plugin/tsconfig.lib.json",
"assets": [],
"project": "packages/runtime-plugins/inject-external-runtime-core-plugin/package.json",
"additionalEntryPoints": [
"packages/runtime-plugins/inject-external-runtime-core-plugin/src/normalize-webpack-path.ts"
],
"rollupConfig": "packages/runtime-plugins/inject-external-runtime-core-plugin/rollup.config.js",
"compiler": "swc",
"generatePackageJson": false,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
"compilerOptions": {
"module": "commonjs",
"forceConsistentCasingInFileNames": true,
"strict": true,
"noImplicitOverride": true,
"noPropertyAccessFromIndexSignature": true,
"noImplicitReturns": true,
Expand Down
Loading
Loading