@module-federation/storybook-addon
Version:
Storybook addon to consume remote module federated apps/components
79 lines • 3.45 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.withModuleFederation = exports.PLUGIN_NAME = void 0;
const node_fs_1 = __importDefault(require("node:fs"));
const node_path_1 = __importDefault(require("node:path"));
const rspack_1 = require("@module-federation/enhanced/rspack");
const sdk_1 = require("@module-federation/sdk");
const correctImportPath_1 = require("./correctImportPath");
const tempDirPath = node_path_1.default.resolve(process.cwd(), `node_modules/${sdk_1.TEMP_DIR}`);
exports.PLUGIN_NAME = 'module-federation-storybook-addon';
// add bootstrap for host project
const bootstrapPath = node_path_1.default.resolve(process.cwd(), `node_modules/${sdk_1.TEMP_DIR}/storybook-bootstrap.js`);
const generateBootstrap = (context, entryPath) => {
return `import('${(0, correctImportPath_1.correctImportPath)(context, entryPath)}');`;
};
const writeBootstrap = (context, entryPath) => {
if (!node_fs_1.default.existsSync(tempDirPath)) {
node_fs_1.default.mkdirSync(tempDirPath);
}
if (node_fs_1.default.existsSync(bootstrapPath)) {
node_fs_1.default.unlinkSync(bootstrapPath);
}
node_fs_1.default.writeFileSync(bootstrapPath, generateBootstrap(context, entryPath));
};
const withModuleFederation = (rsbuildConfig, options) => {
rsbuildConfig.plugins ??= [];
rsbuildConfig.source ??= {};
rsbuildConfig.source.entry ??= {};
const entry = rsbuildConfig.source.entry;
const context = rsbuildConfig.root || process.cwd();
for (const entryName in entry) {
if (Array.isArray(entry[entryName])) {
writeBootstrap(context, entry[entryName][0]);
entry[entryName] = [bootstrapPath];
}
}
const rsbuildPlugin = {
name: 'module-federation-storybook-plugin',
setup: function (api) {
api.modifyRsbuildConfig((config, { mergeRsbuildConfig }) => {
const mfConfig = {
dev: {
// remoteEntry already includes one hmr runtime, and an additional one is not necessary.
hmr: false,
},
};
return mergeRsbuildConfig(config, mfConfig);
});
api.modifyBundlerChain(async (chain) => {
chain.plugin(exports.PLUGIN_NAME).use(rspack_1.ModuleFederationPlugin, [
{
name: options.name || exports.PLUGIN_NAME,
shared: {
react: {
singleton: true,
},
'react-dom': {
singleton: true,
},
...options.shared,
},
remotes: {
...options.remotes,
},
shareStrategy: options.shareStrategy,
},
]);
});
},
};
rsbuildConfig.plugins.push(rsbuildPlugin);
return rsbuildConfig;
};
exports.withModuleFederation = withModuleFederation;
exports.default = exports.withModuleFederation;
//# sourceMappingURL=with-module-federation-enhanced-rsbuild.js.map