From 321c3c5d3c3829a6e32875622f5a51b72c1753d2 Mon Sep 17 00:00:00 2001 From: Andrei Fiodorov Date: Thu, 23 Feb 2023 16:01:49 +0100 Subject: [PATCH 01/29] feat: add package storybook-plugin --- packages/storybook-plugin/.babelrc | 10 ++++ packages/storybook-plugin/.eslintrc.json | 25 +++++++++ packages/storybook-plugin/README.md | 11 ++++ packages/storybook-plugin/jest.config.ts | 15 ++++++ packages/storybook-plugin/package.json | 21 ++++++++ packages/storybook-plugin/project.json | 40 ++++++++++++++ packages/storybook-plugin/src/index.ts | 1 + .../storybook-plugin/src/lib/mf-preview.ts | 23 ++++++++ .../src/lib/storybook-plugin.ts | 52 +++++++++++++++++++ packages/storybook-plugin/tsconfig.json | 22 ++++++++ packages/storybook-plugin/tsconfig.lib.json | 10 ++++ packages/storybook-plugin/tsconfig.spec.json | 14 +++++ tsconfig.base.json | 3 ++ workspace.json | 1 + 14 files changed, 248 insertions(+) create mode 100644 packages/storybook-plugin/.babelrc create mode 100644 packages/storybook-plugin/.eslintrc.json create mode 100644 packages/storybook-plugin/README.md create mode 100644 packages/storybook-plugin/jest.config.ts create mode 100644 packages/storybook-plugin/package.json create mode 100644 packages/storybook-plugin/project.json create mode 100644 packages/storybook-plugin/src/index.ts create mode 100644 packages/storybook-plugin/src/lib/mf-preview.ts create mode 100644 packages/storybook-plugin/src/lib/storybook-plugin.ts create mode 100644 packages/storybook-plugin/tsconfig.json create mode 100644 packages/storybook-plugin/tsconfig.lib.json create mode 100644 packages/storybook-plugin/tsconfig.spec.json diff --git a/packages/storybook-plugin/.babelrc b/packages/storybook-plugin/.babelrc new file mode 100644 index 00000000000..b63f0528f97 --- /dev/null +++ b/packages/storybook-plugin/.babelrc @@ -0,0 +1,10 @@ +{ + "presets": [ + [ + "@nrwl/js/babel", + { + "useBuiltIns": "usage" + } + ] + ] +} diff --git a/packages/storybook-plugin/.eslintrc.json b/packages/storybook-plugin/.eslintrc.json new file mode 100644 index 00000000000..bcc80614588 --- /dev/null +++ b/packages/storybook-plugin/.eslintrc.json @@ -0,0 +1,25 @@ +{ + "extends": ["../../.eslintrc.json"], + "ignorePatterns": ["!**/*"], + "overrides": [ + { + "files": ["*.ts", "*.tsx", "*.js", "*.jsx"], + "rules": { + "@nrwl/nx/enforce-module-boundaries": [ + "error", + { + "allow": ["@storybook/**"] + } + ] + } + }, + { + "files": ["*.ts", "*.tsx"], + "rules": {} + }, + { + "files": ["*.js", "*.jsx"], + "rules": {} + } + ] +} diff --git a/packages/storybook-plugin/README.md b/packages/storybook-plugin/README.md new file mode 100644 index 00000000000..91e1b87a230 --- /dev/null +++ b/packages/storybook-plugin/README.md @@ -0,0 +1,11 @@ +# storybook-plugin + +This library was generated with [Nx](https://nx.dev). + +## Building + +Run `nx build storybook-plugin` to build the library. + +## Running unit tests + +Run `nx test storybook-plugin` to execute the unit tests via [Jest](https://jestjs.io). diff --git a/packages/storybook-plugin/jest.config.ts b/packages/storybook-plugin/jest.config.ts new file mode 100644 index 00000000000..a5055ff284e --- /dev/null +++ b/packages/storybook-plugin/jest.config.ts @@ -0,0 +1,15 @@ +/* eslint-disable */ +export default { + displayName: 'storybook-plugin', + preset: '../../jest.preset.js', + globals: { + 'ts-jest': { + tsconfig: '/tsconfig.spec.json', + }, + }, + transform: { + '^.+\\.[tj]s$': 'ts-jest', + }, + moduleFileExtensions: ['ts', 'js', 'html'], + coverageDirectory: '../../coverage/packages/storybook-plugin', +}; diff --git a/packages/storybook-plugin/package.json b/packages/storybook-plugin/package.json new file mode 100644 index 00000000000..f03f0c37ea6 --- /dev/null +++ b/packages/storybook-plugin/package.json @@ -0,0 +1,21 @@ +{ + "name": "@module-federation/storybook-plugin", + "version": "0.0.1", + "description": "Storybook plugin to consume remote module federated apps/components", + "license": "MIT", + "keywords": [ + "module-federation", + "typescript", + "storybook", + "addon" + ], + "author": "Fiodorov Andrei (https://github.com/fyodorovandrei)", + "devDependencies": { + "@storybook/node-logger": "^6.5.16", + "webpack": "^5.75.0" + }, + "peerDependencies": { + "@storybook/node-logger": "^6.5.16", + "webpack": "^5.75.0" + } +} diff --git a/packages/storybook-plugin/project.json b/packages/storybook-plugin/project.json new file mode 100644 index 00000000000..ffca545ecca --- /dev/null +++ b/packages/storybook-plugin/project.json @@ -0,0 +1,40 @@ +{ + "name": "storybook-plugin", + "$schema": "../../node_modules/nx/schemas/project-schema.json", + "sourceRoot": "packages/storybook-plugin/src", + "projectType": "library", + "targets": { + "build": { + "executor": "@nrwl/js:tsc", + "outputs": ["{options.outputPath}"], + "options": { + "outputPath": "dist/packages/storybook-plugin", + "main": "packages/storybook-plugin/src/index.ts", + "tsConfig": "packages/storybook-plugin/tsconfig.lib.json", + "assets": ["packages/storybook-plugin/*.md"] + } + }, + "lint": { + "executor": "@nrwl/linter:eslint", + "outputs": ["{options.outputFile}"], + "options": { + "lintFilePatterns": ["packages/storybook-plugin/**/*.ts"] + } + }, + "test": { + "executor": "@nrwl/jest:jest", + "outputs": ["{workspaceRoot}/coverage/{projectRoot}"], + "options": { + "jestConfig": "packages/storybook-plugin/jest.config.ts", + "passWithNoTests": true + }, + "configurations": { + "ci": { + "ci": true, + "codeCoverage": true + } + } + } + }, + "tags": [] +} diff --git a/packages/storybook-plugin/src/index.ts b/packages/storybook-plugin/src/index.ts new file mode 100644 index 00000000000..4dcca7f89a4 --- /dev/null +++ b/packages/storybook-plugin/src/index.ts @@ -0,0 +1 @@ +export * from './lib/storybook-plugin'; diff --git a/packages/storybook-plugin/src/lib/mf-preview.ts b/packages/storybook-plugin/src/lib/mf-preview.ts new file mode 100644 index 00000000000..9976aed00ac --- /dev/null +++ b/packages/storybook-plugin/src/lib/mf-preview.ts @@ -0,0 +1,23 @@ +type StoryContext = { + title: string; +}; + +export const parameters = { + docs: { + source: { + type: 'dynamic', + }, + transformSource: (source: string, { title }: StoryContext) => { + // With source dynamic and exclude decorators the output of component is "[object Object]" + // Workaround to replace with component name. + const match = '[object Object]'; + if (source.indexOf(match) !== -1) { + const fullComponentPath = title.split('/'); + const componentName = fullComponentPath[fullComponentPath.length - 1]; + return source.replaceAll(match, componentName); + } + + return source; + }, + }, +}; diff --git a/packages/storybook-plugin/src/lib/storybook-plugin.ts b/packages/storybook-plugin/src/lib/storybook-plugin.ts new file mode 100644 index 00000000000..74df0aa1c05 --- /dev/null +++ b/packages/storybook-plugin/src/lib/storybook-plugin.ts @@ -0,0 +1,52 @@ +import { container, Configuration } from 'webpack'; +import { ModuleFederationPluginOptions } from '@module-federation/utilities'; +import { logger } from '@storybook/node-logger'; + +const { ModuleFederationPlugin } = container; + +type Preset = string | { name: string }; + +type Options = { + moduleFederationConfig: ModuleFederationPluginOptions; + presets: { + apply(preset: Preset): Promise; + }; +}; + +export const webpack = async ( + webpackConfig: Configuration, + options: Options +): Promise => { + const { plugins = [] } = webpackConfig; + const { moduleFederationConfig, presets } = options; + + // Detect webpack version. More about storybook webpack config https://storybook.js.org/docs/react/addons/writing-presets#webpack + const webpackVersion = await presets.apply('webpackVersion'); + logger.info(`=> Webpack ${webpackVersion} version detected`); + + if (webpackVersion !== '5') { + throw new Error( + 'Webpack 5 required: Configure Storybook to use the webpack5 builder' + ); + } + + logger.info(`=> Push Module Federation plugin`); + + plugins.push( + new ModuleFederationPlugin({ + ...moduleFederationConfig, + shared: {}, // TODO: Fix error shared dependencies + }) + ); + + return { + ...webpackConfig, + plugins, + }; +}; + +export const config = (entry: string[] = []): string[] => { + logger.info(`=> Load Module Federation plugin preview file`); + + return [...entry, require.resolve('./mf-preview')]; +}; diff --git a/packages/storybook-plugin/tsconfig.json b/packages/storybook-plugin/tsconfig.json new file mode 100644 index 00000000000..f5b85657a88 --- /dev/null +++ b/packages/storybook-plugin/tsconfig.json @@ -0,0 +1,22 @@ +{ + "extends": "../../tsconfig.base.json", + "compilerOptions": { + "module": "commonjs", + "forceConsistentCasingInFileNames": true, + "strict": true, + "noImplicitOverride": true, + "noPropertyAccessFromIndexSignature": true, + "noImplicitReturns": true, + "noFallthroughCasesInSwitch": true + }, + "files": [], + "include": [], + "references": [ + { + "path": "./tsconfig.lib.json" + }, + { + "path": "./tsconfig.spec.json" + } + ] +} diff --git a/packages/storybook-plugin/tsconfig.lib.json b/packages/storybook-plugin/tsconfig.lib.json new file mode 100644 index 00000000000..33eca2c2cdf --- /dev/null +++ b/packages/storybook-plugin/tsconfig.lib.json @@ -0,0 +1,10 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "outDir": "../../dist/out-tsc", + "declaration": true, + "types": ["node"] + }, + "include": ["src/**/*.ts"], + "exclude": ["jest.config.ts", "src/**/*.spec.ts", "src/**/*.test.ts"] +} diff --git a/packages/storybook-plugin/tsconfig.spec.json b/packages/storybook-plugin/tsconfig.spec.json new file mode 100644 index 00000000000..9b2a121d114 --- /dev/null +++ b/packages/storybook-plugin/tsconfig.spec.json @@ -0,0 +1,14 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "outDir": "../../dist/out-tsc", + "module": "commonjs", + "types": ["jest", "node"] + }, + "include": [ + "jest.config.ts", + "src/**/*.test.ts", + "src/**/*.spec.ts", + "src/**/*.d.ts" + ] +} diff --git a/tsconfig.base.json b/tsconfig.base.json index 15f6073a1d4..b8944a4c0d8 100644 --- a/tsconfig.base.json +++ b/tsconfig.base.json @@ -18,6 +18,9 @@ "paths": { "@module-federation/nextjs-mf": ["packages/nextjs-mf/src/index.ts"], "@module-federation/node": ["packages/node/src/index.ts"], + "@module-federation/storybook-plugin": [ + "packages/storybook-plugin/src/index.ts" + ], "@module-federation/typescript": ["packages/typescript/src/index.ts"], "@module-federation/utilities": ["packages/utilities/src/index.ts"] } diff --git a/workspace.json b/workspace.json index bd476c65a3c..325b95b1351 100644 --- a/workspace.json +++ b/workspace.json @@ -9,6 +9,7 @@ "node": "packages/node", "react-ts-host": "apps/react-ts-host", "react-ts-remote": "apps/react-ts-remote", + "storybook-plugin": "packages/storybook-plugin", "typescript": "packages/typescript", "utils": "packages/utilities" } From d985b195e2919b2d760a36484dc4777681cabb5f Mon Sep 17 00:00:00 2001 From: Andrei Fiodorov Date: Thu, 23 Feb 2023 16:02:19 +0100 Subject: [PATCH 02/29] feat(storybook-plugin): add test for webpack fn --- .../src/lib/storybook-plugin.spec.ts | 60 +++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 packages/storybook-plugin/src/lib/storybook-plugin.spec.ts diff --git a/packages/storybook-plugin/src/lib/storybook-plugin.spec.ts b/packages/storybook-plugin/src/lib/storybook-plugin.spec.ts new file mode 100644 index 00000000000..f5192ce5713 --- /dev/null +++ b/packages/storybook-plugin/src/lib/storybook-plugin.spec.ts @@ -0,0 +1,60 @@ +import { webpack } from './storybook-plugin'; +import { Configuration, container } from 'webpack'; + +const { ModuleFederationPlugin } = container; + +const webpackConfig: Configuration = { + mode: 'production', + entry: './foo.js', + output: { + path: './dist', + filename: 'foo.bundle.js', + }, +}; + +const moduleFederationConfig = { + name: 'host', + remotes: { + remote: 'remote@http://localhost:3002/remoteEntry.js', + }, + shared: {}, +}; + +describe('webpack()', () => { + it('should return error for webpack 4 version', async () => { + const apply = jest.fn().mockResolvedValue(Promise.resolve('4')); + + const presets = { + apply, + }; + + await expect( + webpack(webpackConfig, { + moduleFederationConfig, + presets, + }) + ).rejects.toThrow( + 'Webpack 5 required: Configure Storybook to use the webpack5 builder' + ); + }); + + it('should return config for webpack 5 version', async () => { + const apply = jest.fn().mockResolvedValue(Promise.resolve('5')); + + const presets = { + apply, + }; + + const matchObject = { + ...webpackConfig, + plugins: [new ModuleFederationPlugin(moduleFederationConfig)], + }; + + await expect( + webpack(webpackConfig, { + moduleFederationConfig, + presets, + }) + ).resolves.toMatchObject(matchObject); + }); +}); From df70cd17deb9bd51f60938a0336ef117db455f67 Mon Sep 17 00:00:00 2001 From: Andrei Fiodorov Date: Thu, 23 Feb 2023 16:01:49 +0100 Subject: [PATCH 03/29] feat: add package storybook-plugin --- packages/storybook-plugin/.babelrc | 10 ++++ packages/storybook-plugin/.eslintrc.json | 25 +++++++++ packages/storybook-plugin/README.md | 11 ++++ packages/storybook-plugin/jest.config.ts | 15 ++++++ packages/storybook-plugin/package.json | 21 ++++++++ packages/storybook-plugin/project.json | 40 ++++++++++++++ packages/storybook-plugin/src/index.ts | 1 + .../storybook-plugin/src/lib/mf-preview.ts | 23 ++++++++ .../src/lib/storybook-plugin.ts | 52 +++++++++++++++++++ packages/storybook-plugin/tsconfig.json | 22 ++++++++ packages/storybook-plugin/tsconfig.lib.json | 10 ++++ packages/storybook-plugin/tsconfig.spec.json | 14 +++++ tsconfig.base.json | 3 ++ workspace.json | 1 + 14 files changed, 248 insertions(+) create mode 100644 packages/storybook-plugin/.babelrc create mode 100644 packages/storybook-plugin/.eslintrc.json create mode 100644 packages/storybook-plugin/README.md create mode 100644 packages/storybook-plugin/jest.config.ts create mode 100644 packages/storybook-plugin/package.json create mode 100644 packages/storybook-plugin/project.json create mode 100644 packages/storybook-plugin/src/index.ts create mode 100644 packages/storybook-plugin/src/lib/mf-preview.ts create mode 100644 packages/storybook-plugin/src/lib/storybook-plugin.ts create mode 100644 packages/storybook-plugin/tsconfig.json create mode 100644 packages/storybook-plugin/tsconfig.lib.json create mode 100644 packages/storybook-plugin/tsconfig.spec.json diff --git a/packages/storybook-plugin/.babelrc b/packages/storybook-plugin/.babelrc new file mode 100644 index 00000000000..b63f0528f97 --- /dev/null +++ b/packages/storybook-plugin/.babelrc @@ -0,0 +1,10 @@ +{ + "presets": [ + [ + "@nrwl/js/babel", + { + "useBuiltIns": "usage" + } + ] + ] +} diff --git a/packages/storybook-plugin/.eslintrc.json b/packages/storybook-plugin/.eslintrc.json new file mode 100644 index 00000000000..bcc80614588 --- /dev/null +++ b/packages/storybook-plugin/.eslintrc.json @@ -0,0 +1,25 @@ +{ + "extends": ["../../.eslintrc.json"], + "ignorePatterns": ["!**/*"], + "overrides": [ + { + "files": ["*.ts", "*.tsx", "*.js", "*.jsx"], + "rules": { + "@nrwl/nx/enforce-module-boundaries": [ + "error", + { + "allow": ["@storybook/**"] + } + ] + } + }, + { + "files": ["*.ts", "*.tsx"], + "rules": {} + }, + { + "files": ["*.js", "*.jsx"], + "rules": {} + } + ] +} diff --git a/packages/storybook-plugin/README.md b/packages/storybook-plugin/README.md new file mode 100644 index 00000000000..91e1b87a230 --- /dev/null +++ b/packages/storybook-plugin/README.md @@ -0,0 +1,11 @@ +# storybook-plugin + +This library was generated with [Nx](https://nx.dev). + +## Building + +Run `nx build storybook-plugin` to build the library. + +## Running unit tests + +Run `nx test storybook-plugin` to execute the unit tests via [Jest](https://jestjs.io). diff --git a/packages/storybook-plugin/jest.config.ts b/packages/storybook-plugin/jest.config.ts new file mode 100644 index 00000000000..a5055ff284e --- /dev/null +++ b/packages/storybook-plugin/jest.config.ts @@ -0,0 +1,15 @@ +/* eslint-disable */ +export default { + displayName: 'storybook-plugin', + preset: '../../jest.preset.js', + globals: { + 'ts-jest': { + tsconfig: '/tsconfig.spec.json', + }, + }, + transform: { + '^.+\\.[tj]s$': 'ts-jest', + }, + moduleFileExtensions: ['ts', 'js', 'html'], + coverageDirectory: '../../coverage/packages/storybook-plugin', +}; diff --git a/packages/storybook-plugin/package.json b/packages/storybook-plugin/package.json new file mode 100644 index 00000000000..f03f0c37ea6 --- /dev/null +++ b/packages/storybook-plugin/package.json @@ -0,0 +1,21 @@ +{ + "name": "@module-federation/storybook-plugin", + "version": "0.0.1", + "description": "Storybook plugin to consume remote module federated apps/components", + "license": "MIT", + "keywords": [ + "module-federation", + "typescript", + "storybook", + "addon" + ], + "author": "Fiodorov Andrei (https://github.com/fyodorovandrei)", + "devDependencies": { + "@storybook/node-logger": "^6.5.16", + "webpack": "^5.75.0" + }, + "peerDependencies": { + "@storybook/node-logger": "^6.5.16", + "webpack": "^5.75.0" + } +} diff --git a/packages/storybook-plugin/project.json b/packages/storybook-plugin/project.json new file mode 100644 index 00000000000..ffca545ecca --- /dev/null +++ b/packages/storybook-plugin/project.json @@ -0,0 +1,40 @@ +{ + "name": "storybook-plugin", + "$schema": "../../node_modules/nx/schemas/project-schema.json", + "sourceRoot": "packages/storybook-plugin/src", + "projectType": "library", + "targets": { + "build": { + "executor": "@nrwl/js:tsc", + "outputs": ["{options.outputPath}"], + "options": { + "outputPath": "dist/packages/storybook-plugin", + "main": "packages/storybook-plugin/src/index.ts", + "tsConfig": "packages/storybook-plugin/tsconfig.lib.json", + "assets": ["packages/storybook-plugin/*.md"] + } + }, + "lint": { + "executor": "@nrwl/linter:eslint", + "outputs": ["{options.outputFile}"], + "options": { + "lintFilePatterns": ["packages/storybook-plugin/**/*.ts"] + } + }, + "test": { + "executor": "@nrwl/jest:jest", + "outputs": ["{workspaceRoot}/coverage/{projectRoot}"], + "options": { + "jestConfig": "packages/storybook-plugin/jest.config.ts", + "passWithNoTests": true + }, + "configurations": { + "ci": { + "ci": true, + "codeCoverage": true + } + } + } + }, + "tags": [] +} diff --git a/packages/storybook-plugin/src/index.ts b/packages/storybook-plugin/src/index.ts new file mode 100644 index 00000000000..4dcca7f89a4 --- /dev/null +++ b/packages/storybook-plugin/src/index.ts @@ -0,0 +1 @@ +export * from './lib/storybook-plugin'; diff --git a/packages/storybook-plugin/src/lib/mf-preview.ts b/packages/storybook-plugin/src/lib/mf-preview.ts new file mode 100644 index 00000000000..9976aed00ac --- /dev/null +++ b/packages/storybook-plugin/src/lib/mf-preview.ts @@ -0,0 +1,23 @@ +type StoryContext = { + title: string; +}; + +export const parameters = { + docs: { + source: { + type: 'dynamic', + }, + transformSource: (source: string, { title }: StoryContext) => { + // With source dynamic and exclude decorators the output of component is "[object Object]" + // Workaround to replace with component name. + const match = '[object Object]'; + if (source.indexOf(match) !== -1) { + const fullComponentPath = title.split('/'); + const componentName = fullComponentPath[fullComponentPath.length - 1]; + return source.replaceAll(match, componentName); + } + + return source; + }, + }, +}; diff --git a/packages/storybook-plugin/src/lib/storybook-plugin.ts b/packages/storybook-plugin/src/lib/storybook-plugin.ts new file mode 100644 index 00000000000..74df0aa1c05 --- /dev/null +++ b/packages/storybook-plugin/src/lib/storybook-plugin.ts @@ -0,0 +1,52 @@ +import { container, Configuration } from 'webpack'; +import { ModuleFederationPluginOptions } from '@module-federation/utilities'; +import { logger } from '@storybook/node-logger'; + +const { ModuleFederationPlugin } = container; + +type Preset = string | { name: string }; + +type Options = { + moduleFederationConfig: ModuleFederationPluginOptions; + presets: { + apply(preset: Preset): Promise; + }; +}; + +export const webpack = async ( + webpackConfig: Configuration, + options: Options +): Promise => { + const { plugins = [] } = webpackConfig; + const { moduleFederationConfig, presets } = options; + + // Detect webpack version. More about storybook webpack config https://storybook.js.org/docs/react/addons/writing-presets#webpack + const webpackVersion = await presets.apply('webpackVersion'); + logger.info(`=> Webpack ${webpackVersion} version detected`); + + if (webpackVersion !== '5') { + throw new Error( + 'Webpack 5 required: Configure Storybook to use the webpack5 builder' + ); + } + + logger.info(`=> Push Module Federation plugin`); + + plugins.push( + new ModuleFederationPlugin({ + ...moduleFederationConfig, + shared: {}, // TODO: Fix error shared dependencies + }) + ); + + return { + ...webpackConfig, + plugins, + }; +}; + +export const config = (entry: string[] = []): string[] => { + logger.info(`=> Load Module Federation plugin preview file`); + + return [...entry, require.resolve('./mf-preview')]; +}; diff --git a/packages/storybook-plugin/tsconfig.json b/packages/storybook-plugin/tsconfig.json new file mode 100644 index 00000000000..f5b85657a88 --- /dev/null +++ b/packages/storybook-plugin/tsconfig.json @@ -0,0 +1,22 @@ +{ + "extends": "../../tsconfig.base.json", + "compilerOptions": { + "module": "commonjs", + "forceConsistentCasingInFileNames": true, + "strict": true, + "noImplicitOverride": true, + "noPropertyAccessFromIndexSignature": true, + "noImplicitReturns": true, + "noFallthroughCasesInSwitch": true + }, + "files": [], + "include": [], + "references": [ + { + "path": "./tsconfig.lib.json" + }, + { + "path": "./tsconfig.spec.json" + } + ] +} diff --git a/packages/storybook-plugin/tsconfig.lib.json b/packages/storybook-plugin/tsconfig.lib.json new file mode 100644 index 00000000000..33eca2c2cdf --- /dev/null +++ b/packages/storybook-plugin/tsconfig.lib.json @@ -0,0 +1,10 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "outDir": "../../dist/out-tsc", + "declaration": true, + "types": ["node"] + }, + "include": ["src/**/*.ts"], + "exclude": ["jest.config.ts", "src/**/*.spec.ts", "src/**/*.test.ts"] +} diff --git a/packages/storybook-plugin/tsconfig.spec.json b/packages/storybook-plugin/tsconfig.spec.json new file mode 100644 index 00000000000..9b2a121d114 --- /dev/null +++ b/packages/storybook-plugin/tsconfig.spec.json @@ -0,0 +1,14 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "outDir": "../../dist/out-tsc", + "module": "commonjs", + "types": ["jest", "node"] + }, + "include": [ + "jest.config.ts", + "src/**/*.test.ts", + "src/**/*.spec.ts", + "src/**/*.d.ts" + ] +} diff --git a/tsconfig.base.json b/tsconfig.base.json index 15f6073a1d4..b8944a4c0d8 100644 --- a/tsconfig.base.json +++ b/tsconfig.base.json @@ -18,6 +18,9 @@ "paths": { "@module-federation/nextjs-mf": ["packages/nextjs-mf/src/index.ts"], "@module-federation/node": ["packages/node/src/index.ts"], + "@module-federation/storybook-plugin": [ + "packages/storybook-plugin/src/index.ts" + ], "@module-federation/typescript": ["packages/typescript/src/index.ts"], "@module-federation/utilities": ["packages/utilities/src/index.ts"] } diff --git a/workspace.json b/workspace.json index bd476c65a3c..325b95b1351 100644 --- a/workspace.json +++ b/workspace.json @@ -9,6 +9,7 @@ "node": "packages/node", "react-ts-host": "apps/react-ts-host", "react-ts-remote": "apps/react-ts-remote", + "storybook-plugin": "packages/storybook-plugin", "typescript": "packages/typescript", "utils": "packages/utilities" } From 87c8eb4af0011559e2332fd2177d71d14983a0db Mon Sep 17 00:00:00 2001 From: Andrei Fiodorov Date: Thu, 23 Feb 2023 16:02:19 +0100 Subject: [PATCH 04/29] feat(storybook-plugin): add test for webpack fn --- .../src/lib/storybook-plugin.spec.ts | 60 +++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 packages/storybook-plugin/src/lib/storybook-plugin.spec.ts diff --git a/packages/storybook-plugin/src/lib/storybook-plugin.spec.ts b/packages/storybook-plugin/src/lib/storybook-plugin.spec.ts new file mode 100644 index 00000000000..f5192ce5713 --- /dev/null +++ b/packages/storybook-plugin/src/lib/storybook-plugin.spec.ts @@ -0,0 +1,60 @@ +import { webpack } from './storybook-plugin'; +import { Configuration, container } from 'webpack'; + +const { ModuleFederationPlugin } = container; + +const webpackConfig: Configuration = { + mode: 'production', + entry: './foo.js', + output: { + path: './dist', + filename: 'foo.bundle.js', + }, +}; + +const moduleFederationConfig = { + name: 'host', + remotes: { + remote: 'remote@http://localhost:3002/remoteEntry.js', + }, + shared: {}, +}; + +describe('webpack()', () => { + it('should return error for webpack 4 version', async () => { + const apply = jest.fn().mockResolvedValue(Promise.resolve('4')); + + const presets = { + apply, + }; + + await expect( + webpack(webpackConfig, { + moduleFederationConfig, + presets, + }) + ).rejects.toThrow( + 'Webpack 5 required: Configure Storybook to use the webpack5 builder' + ); + }); + + it('should return config for webpack 5 version', async () => { + const apply = jest.fn().mockResolvedValue(Promise.resolve('5')); + + const presets = { + apply, + }; + + const matchObject = { + ...webpackConfig, + plugins: [new ModuleFederationPlugin(moduleFederationConfig)], + }; + + await expect( + webpack(webpackConfig, { + moduleFederationConfig, + presets, + }) + ).resolves.toMatchObject(matchObject); + }); +}); From 08db8bae75cbfdcc687eceaf2d0ab928144986e5 Mon Sep 17 00:00:00 2001 From: Andrei Fiodorov Date: Fri, 24 Feb 2023 16:16:35 +0100 Subject: [PATCH 05/29] feat(storybook-plugin): remove storybook config overwrite --- .../storybook-plugin/src/lib/mf-preview.ts | 23 ------------------- .../src/lib/storybook-plugin.ts | 6 ----- 2 files changed, 29 deletions(-) delete mode 100644 packages/storybook-plugin/src/lib/mf-preview.ts diff --git a/packages/storybook-plugin/src/lib/mf-preview.ts b/packages/storybook-plugin/src/lib/mf-preview.ts deleted file mode 100644 index 9976aed00ac..00000000000 --- a/packages/storybook-plugin/src/lib/mf-preview.ts +++ /dev/null @@ -1,23 +0,0 @@ -type StoryContext = { - title: string; -}; - -export const parameters = { - docs: { - source: { - type: 'dynamic', - }, - transformSource: (source: string, { title }: StoryContext) => { - // With source dynamic and exclude decorators the output of component is "[object Object]" - // Workaround to replace with component name. - const match = '[object Object]'; - if (source.indexOf(match) !== -1) { - const fullComponentPath = title.split('/'); - const componentName = fullComponentPath[fullComponentPath.length - 1]; - return source.replaceAll(match, componentName); - } - - return source; - }, - }, -}; diff --git a/packages/storybook-plugin/src/lib/storybook-plugin.ts b/packages/storybook-plugin/src/lib/storybook-plugin.ts index 74df0aa1c05..4d307df5f3d 100644 --- a/packages/storybook-plugin/src/lib/storybook-plugin.ts +++ b/packages/storybook-plugin/src/lib/storybook-plugin.ts @@ -44,9 +44,3 @@ export const webpack = async ( plugins, }; }; - -export const config = (entry: string[] = []): string[] => { - logger.info(`=> Load Module Federation plugin preview file`); - - return [...entry, require.resolve('./mf-preview')]; -}; From 777f55e23ee844c9e06113b1671f0e0dbb9a3e07 Mon Sep 17 00:00:00 2001 From: Andrei Fiodorov Date: Wed, 1 Mar 2023 13:16:07 +0100 Subject: [PATCH 06/29] feat(storybook-plugin): replace VirtualModulePlugin from storybook webpack config with another configuration to bootstrap entry file --- packages/storybook-plugin/.eslintrc.json | 2 +- packages/storybook-plugin/package.json | 3 +- .../src/lib/storybook-plugin.ts | 86 +++++++++++++++++-- 3 files changed, 81 insertions(+), 10 deletions(-) diff --git a/packages/storybook-plugin/.eslintrc.json b/packages/storybook-plugin/.eslintrc.json index bcc80614588..284d5d70cf3 100644 --- a/packages/storybook-plugin/.eslintrc.json +++ b/packages/storybook-plugin/.eslintrc.json @@ -8,7 +8,7 @@ "@nrwl/nx/enforce-module-boundaries": [ "error", { - "allow": ["@storybook/**"] + "allow": ["@storybook/**", "fs", "os", "path", "webpack-virtual-modules"] } ] } diff --git a/packages/storybook-plugin/package.json b/packages/storybook-plugin/package.json index f03f0c37ea6..a0365639a8f 100644 --- a/packages/storybook-plugin/package.json +++ b/packages/storybook-plugin/package.json @@ -12,7 +12,8 @@ "author": "Fiodorov Andrei (https://github.com/fyodorovandrei)", "devDependencies": { "@storybook/node-logger": "^6.5.16", - "webpack": "^5.75.0" + "webpack": "^5.75.0", + "webpack-virtual-modules": "^0.5.0" }, "peerDependencies": { "@storybook/node-logger": "^6.5.16", diff --git a/packages/storybook-plugin/src/lib/storybook-plugin.ts b/packages/storybook-plugin/src/lib/storybook-plugin.ts index 4d307df5f3d..908a6c05b5b 100644 --- a/packages/storybook-plugin/src/lib/storybook-plugin.ts +++ b/packages/storybook-plugin/src/lib/storybook-plugin.ts @@ -1,7 +1,30 @@ +import fs from 'fs'; +import os from 'os'; +import path from 'path'; +import VirtualModulesPlugin from 'webpack-virtual-modules'; import { container, Configuration } from 'webpack'; import { ModuleFederationPluginOptions } from '@module-federation/utilities'; import { logger } from '@storybook/node-logger'; +const correctImportPath = (context: string, entryFile: string) => { + if (os.platform() !== 'win32') { + return entryFile; + } + + if (entryFile.match(/^\.?\.\\/) || !entryFile.match(/^[A-Z]:\\\\/i)) { + return entryFile.replace(/\\/g, '/'); + } + + const joint = path.win32.relative(context, entryFile); + const relative = joint.replace(/\\/g, '/'); + + if (relative.includes('node_modules/')) { + return relative.split('node_modules/')[1]; + } + + return `./${relative}`; +}; + const { ModuleFederationPlugin } = container; type Preset = string | { name: string }; @@ -17,12 +40,13 @@ export const webpack = async ( webpackConfig: Configuration, options: Options ): Promise => { - const { plugins = [] } = webpackConfig; + const { plugins = [], entry: webpackEntry, context } = webpackConfig; const { moduleFederationConfig, presets } = options; + let entry = webpackEntry; // Detect webpack version. More about storybook webpack config https://storybook.js.org/docs/react/addons/writing-presets#webpack const webpackVersion = await presets.apply('webpackVersion'); - logger.info(`=> Webpack ${webpackVersion} version detected`); + logger.info(`=> [MF] Webpack ${webpackVersion} version detected`); if (webpackVersion !== '5') { throw new Error( @@ -30,17 +54,63 @@ export const webpack = async ( ); } - logger.info(`=> Push Module Federation plugin`); + logger.info(`=> [MF] Push Module Federation plugin`); + plugins.push(new ModuleFederationPlugin(moduleFederationConfig)); - plugins.push( - new ModuleFederationPlugin({ - ...moduleFederationConfig, - shared: {}, // TODO: Fix error shared dependencies - }) + const index = plugins.findIndex( + (plugin) => plugin.constructor.name === 'VirtualModulesPlugin' ); + if (index !== -1) { + logger.info(`=> [MF] Detected plugin VirtualModulesPlugin`); + + /* eslint-disable @typescript-eslint/no-explicit-any */ + const plugin = plugins[index] as any; + const currenEntryFiles: string[] = Array.isArray(entry) ? entry : []; // TODO: Why if is not array of strings ???? + + const virtualModules = plugin._staticModules; // TODO: Exist another way to get virtual modules? Or maybe it's good idea to open a PR adding a method to get modules? + const virtualModulePaths: string[] = Object.keys(virtualModules); + + // Get modules that are not virtual + const filteredEntry = currenEntryFiles.filter( + (path: string) => !virtualModulePaths.includes(path) + ); + const bootstrap: string[] = filteredEntry.map( + (entryFile: string) => + `import '${correctImportPath(context || process.cwd(), entryFile)}';` + ); + + logger.info(`=> [MF] Write files from VirtualModulesPlugin`); + virtualModulePaths.forEach((virtualModulePath) => { + fs.writeFileSync(virtualModulePath, virtualModules[virtualModulePath]); + bootstrap.push( + `import '${correctImportPath( + context || process.cwd(), + virtualModulePath + )}';` + ); + }); + + /** + * Rewrite VirtualModulesPlugin plugin to fix error "Shared module is not available for eager consumption" + * Entry file content is moved in bootstrap file. More details in the webpack documentation: + * https://webpack.js.org/concepts/module-federation/#uncaught-error-shared-module-is-not-available-for-eager-consumption + * */ + logger.info( + `=> [MF] Rewrite plugin VirtualModulesPlugin to bootstrap entry point` + ); + plugins[index] = new VirtualModulesPlugin({ + './__entry.js': `import('./__bootstrap.js');`, + './__bootstrap.js': bootstrap.join('\n'), + }); + + // replace webpack entry file + entry = ['./__entry.js']; + } + return { ...webpackConfig, + entry, plugins, }; }; From 971df96ff197c0e33ef59f0e7ad9be41edafd17a Mon Sep 17 00:00:00 2001 From: Andrei Fiodorov Date: Wed, 1 Mar 2023 20:51:14 +0100 Subject: [PATCH 07/29] fix(storybook-plugin): update todo comment --- packages/storybook-plugin/src/lib/storybook-plugin.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/storybook-plugin/src/lib/storybook-plugin.ts b/packages/storybook-plugin/src/lib/storybook-plugin.ts index 908a6c05b5b..b87fb778c29 100644 --- a/packages/storybook-plugin/src/lib/storybook-plugin.ts +++ b/packages/storybook-plugin/src/lib/storybook-plugin.ts @@ -66,7 +66,7 @@ export const webpack = async ( /* eslint-disable @typescript-eslint/no-explicit-any */ const plugin = plugins[index] as any; - const currenEntryFiles: string[] = Array.isArray(entry) ? entry : []; // TODO: Why if is not array of strings ???? + const currenEntryFiles: string[] = Array.isArray(entry) ? entry : []; // TODO: If is not array of strings ???? const virtualModules = plugin._staticModules; // TODO: Exist another way to get virtual modules? Or maybe it's good idea to open a PR adding a method to get modules? const virtualModulePaths: string[] = Object.keys(virtualModules); From 0e756eedbd6a9a4ae3fa52436cf1a8771f2292c2 Mon Sep 17 00:00:00 2001 From: Andrei Fiodorov Date: Wed, 1 Mar 2023 21:00:15 +0100 Subject: [PATCH 08/29] fix(storybook-plugin): remove preview file --- .../storybook-plugin/src/lib/mf-preview.ts | 23 ------------------- 1 file changed, 23 deletions(-) delete mode 100644 packages/storybook-plugin/src/lib/mf-preview.ts diff --git a/packages/storybook-plugin/src/lib/mf-preview.ts b/packages/storybook-plugin/src/lib/mf-preview.ts deleted file mode 100644 index 9976aed00ac..00000000000 --- a/packages/storybook-plugin/src/lib/mf-preview.ts +++ /dev/null @@ -1,23 +0,0 @@ -type StoryContext = { - title: string; -}; - -export const parameters = { - docs: { - source: { - type: 'dynamic', - }, - transformSource: (source: string, { title }: StoryContext) => { - // With source dynamic and exclude decorators the output of component is "[object Object]" - // Workaround to replace with component name. - const match = '[object Object]'; - if (source.indexOf(match) !== -1) { - const fullComponentPath = title.split('/'); - const componentName = fullComponentPath[fullComponentPath.length - 1]; - return source.replaceAll(match, componentName); - } - - return source; - }, - }, -}; From 165438b92835f3d286dcbc0d77211712f5e35383 Mon Sep 17 00:00:00 2001 From: Andrei Fiodorov Date: Wed, 1 Mar 2023 21:05:08 +0100 Subject: [PATCH 09/29] feat(storybook-plugin): move utils in own folder --- .../src/lib/storybook-plugin.ts | 22 +------------------ packages/storybook-plugin/src/utils/index.ts | 1 + packages/storybook-plugin/src/utils/path.ts | 21 ++++++++++++++++++ 3 files changed, 23 insertions(+), 21 deletions(-) create mode 100644 packages/storybook-plugin/src/utils/index.ts create mode 100644 packages/storybook-plugin/src/utils/path.ts diff --git a/packages/storybook-plugin/src/lib/storybook-plugin.ts b/packages/storybook-plugin/src/lib/storybook-plugin.ts index b87fb778c29..a8d68565fcd 100644 --- a/packages/storybook-plugin/src/lib/storybook-plugin.ts +++ b/packages/storybook-plugin/src/lib/storybook-plugin.ts @@ -1,29 +1,9 @@ import fs from 'fs'; -import os from 'os'; -import path from 'path'; import VirtualModulesPlugin from 'webpack-virtual-modules'; import { container, Configuration } from 'webpack'; import { ModuleFederationPluginOptions } from '@module-federation/utilities'; import { logger } from '@storybook/node-logger'; - -const correctImportPath = (context: string, entryFile: string) => { - if (os.platform() !== 'win32') { - return entryFile; - } - - if (entryFile.match(/^\.?\.\\/) || !entryFile.match(/^[A-Z]:\\\\/i)) { - return entryFile.replace(/\\/g, '/'); - } - - const joint = path.win32.relative(context, entryFile); - const relative = joint.replace(/\\/g, '/'); - - if (relative.includes('node_modules/')) { - return relative.split('node_modules/')[1]; - } - - return `./${relative}`; -}; +import { correctImportPath } from '../utils'; const { ModuleFederationPlugin } = container; diff --git a/packages/storybook-plugin/src/utils/index.ts b/packages/storybook-plugin/src/utils/index.ts new file mode 100644 index 00000000000..44bb0aa0469 --- /dev/null +++ b/packages/storybook-plugin/src/utils/index.ts @@ -0,0 +1 @@ +export * from './path'; diff --git a/packages/storybook-plugin/src/utils/path.ts b/packages/storybook-plugin/src/utils/path.ts new file mode 100644 index 00000000000..2ce43f82986 --- /dev/null +++ b/packages/storybook-plugin/src/utils/path.ts @@ -0,0 +1,21 @@ +import os from 'os'; +import path from 'path'; + +export const correctImportPath = (context: string, entryFile: string) => { + if (os.platform() !== 'win32') { + return entryFile; + } + + if (entryFile.match(/^\.?\.\\/) || !entryFile.match(/^[A-Z]:\\\\/i)) { + return entryFile.replace(/\\/g, '/'); + } + + const joint = path.win32.relative(context, entryFile); + const relative = joint.replace(/\\/g, '/'); + + if (relative.includes('node_modules/')) { + return relative.split('node_modules/')[1]; + } + + return `./${relative}`; +}; From a5cda56b912183a20834f5f4dd1fa24891213ac0 Mon Sep 17 00:00:00 2001 From: Andrei Fiodorov Date: Wed, 1 Mar 2023 22:19:06 +0100 Subject: [PATCH 10/29] feat(storybook-plugin): update logic to replace or push the plugin VirtualModulePlugin --- .../src/lib/storybook-plugin.ts | 66 +++++++++---------- 1 file changed, 33 insertions(+), 33 deletions(-) diff --git a/packages/storybook-plugin/src/lib/storybook-plugin.ts b/packages/storybook-plugin/src/lib/storybook-plugin.ts index a8d68565fcd..8204e01613b 100644 --- a/packages/storybook-plugin/src/lib/storybook-plugin.ts +++ b/packages/storybook-plugin/src/lib/storybook-plugin.ts @@ -20,9 +20,8 @@ export const webpack = async ( webpackConfig: Configuration, options: Options ): Promise => { - const { plugins = [], entry: webpackEntry, context } = webpackConfig; + const { plugins = [], context } = webpackConfig; const { moduleFederationConfig, presets } = options; - let entry = webpackEntry; // Detect webpack version. More about storybook webpack config https://storybook.js.org/docs/react/addons/writing-presets#webpack const webpackVersion = await presets.apply('webpackVersion'); @@ -37,6 +36,12 @@ export const webpack = async ( logger.info(`=> [MF] Push Module Federation plugin`); plugins.push(new ModuleFederationPlugin(moduleFederationConfig)); + const entries = await presets.apply('entries'); + const bootstrap: string[] = entries.map( + (entryFile: string) => + `import '${correctImportPath(context || process.cwd(), entryFile)}';` + ); + const index = plugins.findIndex( (plugin) => plugin.constructor.name === 'VirtualModulesPlugin' ); @@ -46,51 +51,46 @@ export const webpack = async ( /* eslint-disable @typescript-eslint/no-explicit-any */ const plugin = plugins[index] as any; - const currenEntryFiles: string[] = Array.isArray(entry) ? entry : []; // TODO: If is not array of strings ???? - - const virtualModules = plugin._staticModules; // TODO: Exist another way to get virtual modules? Or maybe it's good idea to open a PR adding a method to get modules? - const virtualModulePaths: string[] = Object.keys(virtualModules); - // Get modules that are not virtual - const filteredEntry = currenEntryFiles.filter( - (path: string) => !virtualModulePaths.includes(path) - ); - const bootstrap: string[] = filteredEntry.map( - (entryFile: string) => - `import '${correctImportPath(context || process.cwd(), entryFile)}';` - ); + const virtualEntries = plugin._staticModules; // TODO: Exist another way to get virtual modules? Or maybe it's good idea to open a PR adding a method to get modules? + const virtualEntriesPaths: string[] = Object.keys(virtualEntries); logger.info(`=> [MF] Write files from VirtualModulesPlugin`); - virtualModulePaths.forEach((virtualModulePath) => { - fs.writeFileSync(virtualModulePath, virtualModules[virtualModulePath]); + virtualEntriesPaths.forEach((virtualEntryPath) => { + fs.writeFileSync(virtualEntryPath, virtualEntries[virtualEntryPath]); bootstrap.push( `import '${correctImportPath( context || process.cwd(), - virtualModulePath + virtualEntryPath )}';` ); }); + } - /** - * Rewrite VirtualModulesPlugin plugin to fix error "Shared module is not available for eager consumption" - * Entry file content is moved in bootstrap file. More details in the webpack documentation: - * https://webpack.js.org/concepts/module-federation/#uncaught-error-shared-module-is-not-available-for-eager-consumption - * */ - logger.info( - `=> [MF] Rewrite plugin VirtualModulesPlugin to bootstrap entry point` - ); - plugins[index] = new VirtualModulesPlugin({ - './__entry.js': `import('./__bootstrap.js');`, - './__bootstrap.js': bootstrap.join('\n'), - }); - - // replace webpack entry file - entry = ['./__entry.js']; + /** + * Create a new VirtualModulesPlugin plugin to fix error "Shared module is not available for eager consumption" + * Entry file content is moved in bootstrap file. More details in the webpack documentation: + * https://webpack.js.org/concepts/module-federation/#uncaught-error-shared-module-is-not-available-for-eager-consumption + * */ + const virtualModulePlugin = new VirtualModulesPlugin({ + './__entry.js': `import('./__bootstrap.js');`, + './__bootstrap.js': bootstrap.join('\n'), + }); + + let action = 'Push'; + if (index === -1) { + plugins.push(virtualModulePlugin); + } else { + plugins[index] = virtualModulePlugin; + action = 'Replace'; } + logger.info( + `=> [MF] ${action} plugin VirtualModulesPlugin to bootstrap entry point` + ); return { ...webpackConfig, - entry, + entry: ['./__entry.js'], plugins, }; }; From c358b697cd21f9fd6b320c73c68cdd286b27808c Mon Sep 17 00:00:00 2001 From: Andrei Fiodorov Date: Wed, 1 Mar 2023 22:51:09 +0100 Subject: [PATCH 11/29] feat(storybook-plugin): fix package description --- packages/storybook-plugin/package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/storybook-plugin/package.json b/packages/storybook-plugin/package.json index a0365639a8f..b80b554ab76 100644 --- a/packages/storybook-plugin/package.json +++ b/packages/storybook-plugin/package.json @@ -1,7 +1,7 @@ { "name": "@module-federation/storybook-plugin", "version": "0.0.1", - "description": "Storybook plugin to consume remote module federated apps/components", + "description": "Storybook addon to consume remote module federated apps/components", "license": "MIT", "keywords": [ "module-federation", From 607ec12dd27bd681f8f1cfa21fcff1086834f770 Mon Sep 17 00:00:00 2001 From: Andrei Fiodorov Date: Wed, 1 Mar 2023 22:51:15 +0100 Subject: [PATCH 12/29] feat(storybook-plugin): update README.md --- packages/storybook-plugin/README.md | 83 ++++++++++++++++++++++++++--- 1 file changed, 77 insertions(+), 6 deletions(-) diff --git a/packages/storybook-plugin/README.md b/packages/storybook-plugin/README.md index 91e1b87a230..17cfe486fc5 100644 --- a/packages/storybook-plugin/README.md +++ b/packages/storybook-plugin/README.md @@ -1,11 +1,82 @@ -# storybook-plugin +# Storybook addon for Module Federation -This library was generated with [Nx](https://nx.dev). +This addon enables to consume remote Module Federated apps/components -## Building +## Install -Run `nx build storybook-plugin` to build the library. +```shell +# with NPM +npm install @module-federation/storybook-plugin -## Running unit tests +# with Yarn +yarn add @module-federation/storybook-plugin +``` -Run `nx test storybook-plugin` to execute the unit tests via [Jest](https://jestjs.io). +## Configuration + +In file `./storybook/main.js`: +```js +const moduleFederationConfig = { + // Module Federation config +}; + +const storybookConfig = { + "stories": [ + "../src/**/*.stories.mdx", + "../src/**/*.stories.@(js|jsx|ts|tsx)" + ], + "addons": [ + // other addons, + { + name: "@module-federation/storybook-plugin", + options: { + moduleFederationConfig + } + } + ], + "framework": "@storybook/react", + "core": { + "builder": "@storybook/builder-webpack5" // is required webpack 5 builder + } +}; + +module.exports = storybookConfig; +``` + +## Usage + +```jsx +import React, { Suspense } from 'react'; + +const LazyButton = React.lazy(() => import('remote/Button')); + +const Button = (props) => ( + Please wait...

}>
+); + +export default { + title: 'ModuleFederation/Button', + component: Button, + argTypes: { + variant: { + control: 'select', + options: ['primary', 'secondary'] + }, + }, +}; + +const Template = (args) => + ); + } +); + +export default Button; diff --git a/apps/react-remote-ui/src/Button/index.ts b/apps/react-remote-ui/src/Button/index.ts new file mode 100644 index 00000000000..efe8c800c0d --- /dev/null +++ b/apps/react-remote-ui/src/Button/index.ts @@ -0,0 +1 @@ +export { default } from './Button'; diff --git a/apps/react-remote-ui/src/bootstrap.tsx b/apps/react-remote-ui/src/bootstrap.tsx new file mode 100644 index 00000000000..e814bcfe145 --- /dev/null +++ b/apps/react-remote-ui/src/bootstrap.tsx @@ -0,0 +1,16 @@ +import { StrictMode } from 'react'; +import * as ReactDOM from 'react-dom/client'; + +import Button from './Button'; + +const root = ReactDOM.createRoot( + document.getElementById('root') as HTMLElement +); +root.render( + +
+ UI Library Button: + +
+
+); diff --git a/apps/react-remote-ui/src/environments/environment.prod.ts b/apps/react-remote-ui/src/environments/environment.prod.ts new file mode 100644 index 00000000000..c9669790be1 --- /dev/null +++ b/apps/react-remote-ui/src/environments/environment.prod.ts @@ -0,0 +1,3 @@ +export const environment = { + production: true, +}; diff --git a/apps/react-remote-ui/src/environments/environment.ts b/apps/react-remote-ui/src/environments/environment.ts new file mode 100644 index 00000000000..7ed83767fff --- /dev/null +++ b/apps/react-remote-ui/src/environments/environment.ts @@ -0,0 +1,6 @@ +// This file can be replaced during build by using the `fileReplacements` array. +// When building for production, this file is replaced with `environment.prod.ts`. + +export const environment = { + production: false, +}; diff --git a/apps/react-remote-ui/src/favicon.ico b/apps/react-remote-ui/src/favicon.ico new file mode 100644 index 0000000000000000000000000000000000000000..317ebcb2336e0833a22dddf0ab287849f26fda57 GIT binary patch literal 15086 zcmeI332;U^%p|z7g|#(P)qFEA@4f!_@qOK2 z_lJl}!lhL!VT_U|uN7%8B2iKH??xhDa;*`g{yjTFWHvXn;2s{4R7kH|pKGdy(7z!K zgftM+Ku7~24TLlh(!g)gz|foI94G^t2^IO$uvX$3(OR0<_5L2sB)lMAMy|+`xodJ{ z_Uh_1m)~h?a;2W{dmhM;u!YGo=)OdmId_B<%^V^{ovI@y`7^g1_V9G}*f# zNzAtvou}I!W1#{M^@ROc(BZ! z+F!!_aR&Px3_reO(EW+TwlW~tv*2zr?iP7(d~a~yA|@*a89IUke+c472NXM0wiX{- zl`UrZC^1XYyf%1u)-Y)jj9;MZ!SLfd2Hl?o|80Su%Z?To_=^g_Jt0oa#CT*tjx>BI z16wec&AOWNK<#i0Qd=1O$fymLRoUR*%;h@*@v7}wApDl^w*h}!sYq%kw+DKDY)@&A z@9$ULEB3qkR#85`lb8#WZw=@})#kQig9oqy^I$dj&k4jU&^2(M3q{n1AKeGUKPFbr z1^<)aH;VsG@J|B&l>UtU#Ejv3GIqERzYgL@UOAWtW<{p#zy`WyJgpCy8$c_e%wYJL zyGHRRx38)HyjU3y{-4z6)pzb>&Q1pR)B&u01F-|&Gx4EZWK$nkUkOI|(D4UHOXg_- zw{OBf!oWQUn)Pe(=f=nt=zkmdjpO^o8ZZ9o_|4tW1ni+Un9iCW47*-ut$KQOww!;u z`0q)$s6IZO!~9$e_P9X!hqLxu`fpcL|2f^I5d4*a@Dq28;@2271v_N+5HqYZ>x;&O z05*7JT)mUe&%S0@UD)@&8SmQrMtsDfZT;fkdA!r(S=}Oz>iP)w=W508=Rc#nNn7ym z1;42c|8($ALY8#a({%1#IXbWn9-Y|0eDY$_L&j{63?{?AH{);EzcqfydD$@-B`Y3<%IIj7S7rK_N}je^=dEk%JQ4c z!tBdTPE3Tse;oYF>cnrapWq*o)m47X1`~6@(!Y29#>-#8zm&LXrXa(3=7Z)ElaQqj z-#0JJy3Fi(C#Rx(`=VXtJ63E2_bZGCz+QRa{W0e2(m3sI?LOcUBx)~^YCqZ{XEPX)C>G>U4tfqeH8L(3|pQR*zbL1 zT9e~4Tb5p9_G}$y4t`i*4t_Mr9QYvL9C&Ah*}t`q*}S+VYh0M6GxTTSXI)hMpMpIq zD1ImYqJLzbj0}~EpE-aH#VCH_udYEW#`P2zYmi&xSPs_{n6tBj=MY|-XrA;SGA_>y zGtU$?HXm$gYj*!N)_nQ59%lQdXtQZS3*#PC-{iB_sm+ytD*7j`D*k(P&IH2GHT}Eh z5697eQECVIGQAUe#eU2I!yI&%0CP#>%6MWV z@zS!p@+Y1i1b^QuuEF*13CuB zu69dve5k7&Wgb+^s|UB08Dr3u`h@yM0NTj4h7MnHo-4@xmyr7(*4$rpPwsCDZ@2be zRz9V^GnV;;?^Lk%ynzq&K(Aix`mWmW`^152Hoy$CTYVehpD-S1-W^#k#{0^L`V6CN+E z!w+xte;2vu4AmVNEFUOBmrBL>6MK@!O2*N|2=d|Y;oN&A&qv=qKn73lDD zI(+oJAdgv>Yr}8(&@ZuAZE%XUXmX(U!N+Z_sjL<1vjy1R+1IeHt`79fnYdOL{$ci7 z%3f0A*;Zt@ED&Gjm|OFTYBDe%bbo*xXAQsFz+Q`fVBH!N2)kaxN8P$c>sp~QXnv>b zwq=W3&Mtmih7xkR$YA)1Yi?avHNR6C99!u6fh=cL|KQ&PwF!n@ud^n(HNIImHD!h87!i*t?G|p0o+eelJ?B@A64_9%SBhNaJ64EvKgD&%LjLCYnNfc; znj?%*p@*?dq#NqcQFmmX($wms@CSAr9#>hUR^=I+=0B)vvGX%T&#h$kmX*s=^M2E!@N9#m?LhMvz}YB+kd zG~mbP|D(;{s_#;hsKK9lbVK&Lo734x7SIFJ9V_}2$@q?zm^7?*XH94w5Qae{7zOMUF z^?%F%)c1Y)Q?Iy?I>knw*8gYW#ok|2gdS=YYZLiD=CW|Nj;n^x!=S#iJ#`~Ld79+xXpVmUK^B(xO_vO!btA9y7w3L3-0j-y4 z?M-V{%z;JI`bk7yFDcP}OcCd*{Q9S5$iGA7*E1@tfkyjAi!;wP^O71cZ^Ep)qrQ)N z#wqw0_HS;T7x3y|`P==i3hEwK%|>fZ)c&@kgKO1~5<5xBSk?iZV?KI6&i72H6S9A* z=U(*e)EqEs?Oc04)V-~K5AUmh|62H4*`UAtItO$O(q5?6jj+K^oD!04r=6#dsxp?~}{`?&sXn#q2 zGuY~7>O2=!u@@Kfu7q=W*4egu@qPMRM>(eyYyaIE<|j%d=iWNdGsx%c!902v#ngNg z@#U-O_4xN$s_9?(`{>{>7~-6FgWpBpqXb`Ydc3OFL#&I}Irse9F_8R@4zSS*Y*o*B zXL?6*Aw!AfkNCgcr#*yj&p3ZDe2y>v$>FUdKIy_2N~}6AbHc7gA3`6$g@1o|dE>vz z4pl(j9;kyMsjaw}lO?(?Xg%4k!5%^t#@5n=WVc&JRa+XT$~#@rldvN3S1rEpU$;XgxVny7mki3 z-Hh|jUCHrUXuLr!)`w>wgO0N%KTB-1di>cj(x3Bav`7v z3G7EIbU$z>`Nad7Rk_&OT-W{;qg)-GXV-aJT#(ozdmnA~Rq3GQ_3mby(>q6Ocb-RgTUhTN)))x>m&eD;$J5Bg zo&DhY36Yg=J=$Z>t}RJ>o|@hAcwWzN#r(WJ52^g$lh^!63@hh+dR$&_dEGu&^CR*< z!oFqSqO@>xZ*nC2oiOd0eS*F^IL~W-rsrO`J`ej{=ou_q^_(<$&-3f^J z&L^MSYWIe{&pYq&9eGaArA~*kA + + + + ReactRemoteUi + + + + + + +
+ + diff --git a/apps/react-remote-ui/src/main.ts b/apps/react-remote-ui/src/main.ts new file mode 100644 index 00000000000..b93c7a0268a --- /dev/null +++ b/apps/react-remote-ui/src/main.ts @@ -0,0 +1 @@ +import('./bootstrap'); diff --git a/apps/react-remote-ui/src/styles.scss b/apps/react-remote-ui/src/styles.scss new file mode 100644 index 00000000000..90d4ee0072c --- /dev/null +++ b/apps/react-remote-ui/src/styles.scss @@ -0,0 +1 @@ +/* You can add global styles to this file, and also import other style files */ diff --git a/apps/react-remote-ui/tsconfig.app.json b/apps/react-remote-ui/tsconfig.app.json new file mode 100644 index 00000000000..ce8082f13b0 --- /dev/null +++ b/apps/react-remote-ui/tsconfig.app.json @@ -0,0 +1,23 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "outDir": "../../dist/out-tsc", + "types": ["node"] + }, + "files": [ + "../../node_modules/@nrwl/react/typings/cssmodule.d.ts", + "../../node_modules/@nrwl/react/typings/image.d.ts" + ], + "exclude": [ + "jest.config.ts", + "src/**/*.spec.ts", + "src/**/*.test.ts", + "src/**/*.spec.tsx", + "src/**/*.test.tsx", + "src/**/*.spec.js", + "src/**/*.test.js", + "src/**/*.spec.jsx", + "src/**/*.test.jsx" + ], + "include": ["src/**/*.js", "src/**/*.jsx", "src/**/*.ts", "src/**/*.tsx"] +} diff --git a/apps/react-remote-ui/tsconfig.json b/apps/react-remote-ui/tsconfig.json new file mode 100644 index 00000000000..3f5f7993c3e --- /dev/null +++ b/apps/react-remote-ui/tsconfig.json @@ -0,0 +1,20 @@ +{ + "compilerOptions": { + "jsx": "react-jsx", + "allowJs": false, + "esModuleInterop": false, + "allowSyntheticDefaultImports": true, + "strict": true, + }, + "files": [], + "include": [], + "references": [ + { + "path": "./tsconfig.app.json" + }, + { + "path": "./tsconfig.spec.json" + } + ], + "extends": "../../tsconfig.base.json" +} diff --git a/apps/react-remote-ui/tsconfig.spec.json b/apps/react-remote-ui/tsconfig.spec.json new file mode 100644 index 00000000000..3100599036f --- /dev/null +++ b/apps/react-remote-ui/tsconfig.spec.json @@ -0,0 +1,24 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "outDir": "../../dist/out-tsc", + "module": "commonjs", + "types": ["jest", "node"] + }, + "include": [ + "jest.config.ts", + "src/**/*.test.ts", + "src/**/*.spec.ts", + "src/**/*.test.tsx", + "src/**/*.spec.tsx", + "src/**/*.test.js", + "src/**/*.spec.js", + "src/**/*.test.jsx", + "src/**/*.spec.jsx", + "src/**/*.d.ts" + ], + "files": [ + "../../node_modules/@nrwl/react/typings/cssmodule.d.ts", + "../../node_modules/@nrwl/react/typings/image.d.ts" + ] +} diff --git a/apps/react-remote-ui/webpack.config.js b/apps/react-remote-ui/webpack.config.js new file mode 100644 index 00000000000..5b6c601ba64 --- /dev/null +++ b/apps/react-remote-ui/webpack.config.js @@ -0,0 +1,16 @@ +const { composePlugins, withNx } = require('@nrwl/webpack'); +const { withReact } = require('@nrwl/react'); +const { withModuleFederation } = require('@nrwl/react/module-federation'); + +const baseConfig = require('./module-federation.config'); + +const config = { + ...baseConfig, +}; + +// Nx plugins for webpack to build config object from Nx options and context. +module.exports = composePlugins( + withNx(), + withReact(), + withModuleFederation(config) +); diff --git a/apps/react-remote-ui/webpack.config.prod.js b/apps/react-remote-ui/webpack.config.prod.js new file mode 100644 index 00000000000..0c9447dffca --- /dev/null +++ b/apps/react-remote-ui/webpack.config.prod.js @@ -0,0 +1 @@ +module.exports = require('./webpack.config'); diff --git a/apps/react-storybook/.babelrc b/apps/react-storybook/.babelrc new file mode 100644 index 00000000000..61641ec8ac3 --- /dev/null +++ b/apps/react-storybook/.babelrc @@ -0,0 +1,11 @@ +{ + "presets": [ + [ + "@nrwl/react/babel", + { + "runtime": "automatic" + } + ] + ], + "plugins": [] +} diff --git a/apps/react-storybook/.eslintrc.json b/apps/react-storybook/.eslintrc.json new file mode 100644 index 00000000000..734ddaceea4 --- /dev/null +++ b/apps/react-storybook/.eslintrc.json @@ -0,0 +1,18 @@ +{ + "extends": ["plugin:@nrwl/nx/react", "../../.eslintrc.json"], + "ignorePatterns": ["!**/*"], + "overrides": [ + { + "files": ["*.ts", "*.tsx", "*.js", "*.jsx"], + "rules": {} + }, + { + "files": ["*.ts", "*.tsx"], + "rules": {} + }, + { + "files": ["*.js", "*.jsx"], + "rules": {} + } + ] +} diff --git a/apps/react-storybook/.storybook/main.js b/apps/react-storybook/.storybook/main.js new file mode 100644 index 00000000000..096c176317e --- /dev/null +++ b/apps/react-storybook/.storybook/main.js @@ -0,0 +1,23 @@ +const nxModuleFederationConfig = require('../module-federation.config'); + +module.exports = { + core: { builder: 'webpack5' }, + stories: [ + '../src/app/**/*.stories.mdx', + '../src/app/**/*.stories.@(js|jsx|ts|tsx)', + ], + addons: [ + '@storybook/addon-essentials', + '@nrwl/react/plugins/storybook', + { + name: '@module-federation/storybook-addon', + options: { + nxMfConfig: { ...nxModuleFederationConfig }, + }, + }, + ], +}; + +// To customize your webpack configuration you can use the webpackFinal field. +// Check https://storybook.js.org/docs/react/builders/webpack#extending-storybooks-webpack-config +// and https://nx.dev/packages/storybook/documents/custom-builder-configs diff --git a/apps/react-storybook/.storybook/preview.js b/apps/react-storybook/.storybook/preview.js new file mode 100644 index 00000000000..e69de29bb2d diff --git a/apps/react-storybook/.storybook/tsconfig.json b/apps/react-storybook/.storybook/tsconfig.json new file mode 100644 index 00000000000..286dc2f6355 --- /dev/null +++ b/apps/react-storybook/.storybook/tsconfig.json @@ -0,0 +1,26 @@ +{ + "extends": "../tsconfig.json", + "compilerOptions": { + "emitDecoratorMetadata": true, + "outDir": "" + }, + "files": [ + "../../../node_modules/@nrwl/react/typings/styled-jsx.d.ts", + "../../../node_modules/@nrwl/react/typings/cssmodule.d.ts", + "../../../node_modules/@nrwl/react/typings/image.d.ts" + ], + "exclude": [ + "../**/*.spec.ts", + "../**/*.spec.js", + "../**/*.spec.tsx", + "../**/*.spec.jsx" + ], + "include": [ + "../src/**/*.stories.ts", + "../src/**/*.stories.js", + "../src/**/*.stories.jsx", + "../src/**/*.stories.tsx", + "../src/**/*.stories.mdx", + "*.js" + ] +} diff --git a/apps/react-storybook/jest.config.ts b/apps/react-storybook/jest.config.ts new file mode 100644 index 00000000000..dcef7ffd444 --- /dev/null +++ b/apps/react-storybook/jest.config.ts @@ -0,0 +1,11 @@ +/* eslint-disable */ +export default { + displayName: 'react-storybook', + preset: '../../jest.preset.js', + transform: { + '^(?!.*\\.(js|jsx|ts|tsx|css|json)$)': '@nrwl/react/plugins/jest', + '^.+\\.[tj]sx?$': ['babel-jest', { presets: ['@nrwl/react/babel'] }], + }, + moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx'], + coverageDirectory: '../../coverage/apps/react-storybook', +}; diff --git a/apps/react-storybook/module-federation.config.js b/apps/react-storybook/module-federation.config.js new file mode 100644 index 00000000000..37f8a23da3c --- /dev/null +++ b/apps/react-storybook/module-federation.config.js @@ -0,0 +1,4 @@ +module.exports = { + name: 'react-storybook', + remotes: ['react-remote-ui'], +}; diff --git a/apps/react-storybook/project.json b/apps/react-storybook/project.json new file mode 100644 index 00000000000..f60bbc0001f --- /dev/null +++ b/apps/react-storybook/project.json @@ -0,0 +1,135 @@ +{ + "name": "react-storybook", + "$schema": "../../node_modules/nx/schemas/project-schema.json", + "sourceRoot": "apps/react-storybook/src", + "projectType": "application", + "targets": { + "build": { + "executor": "@nrwl/webpack:webpack", + "outputs": ["{options.outputPath}"], + "defaultConfiguration": "production", + "options": { + "compiler": "babel", + "outputPath": "dist/apps/react-storybook", + "index": "apps/react-storybook/src/index.html", + "baseHref": "/", + "main": "apps/react-storybook/src/main.ts", + "tsConfig": "apps/react-storybook/tsconfig.app.json", + "assets": [ + "apps/react-storybook/src/favicon.ico", + "apps/react-storybook/src/assets" + ], + "styles": ["apps/react-storybook/src/styles.scss"], + "scripts": [], + "isolatedConfig": true, + "webpackConfig": "apps/react-storybook/webpack.config.js" + }, + "configurations": { + "development": { + "extractLicenses": false, + "optimization": false, + "sourceMap": true, + "vendorChunk": true + }, + "production": { + "fileReplacements": [ + { + "replace": "apps/react-storybook/src/environments/environment.ts", + "with": "apps/react-storybook/src/environments/environment.prod.ts" + } + ], + "optimization": true, + "outputHashing": "all", + "sourceMap": false, + "namedChunks": false, + "extractLicenses": true, + "vendorChunk": false, + "webpackConfig": "apps/react-storybook/webpack.config.prod.js" + } + } + }, + "serve": { + "executor": "@nrwl/react:module-federation-dev-server", + "defaultConfiguration": "development", + "options": { + "buildTarget": "react-storybook:build", + "hmr": true, + "port": 4200 + }, + "configurations": { + "development": { + "buildTarget": "react-storybook:build:development" + }, + "production": { + "buildTarget": "react-storybook:build:production", + "hmr": false + } + } + }, + "lint": { + "executor": "@nrwl/linter:eslint", + "outputs": ["{options.outputFile}"], + "options": { + "lintFilePatterns": ["apps/react-storybook/**/*.{ts,tsx,js,jsx}"] + } + }, + "test": { + "executor": "@nrwl/jest:jest", + "outputs": ["{workspaceRoot}/coverage/{projectRoot}"], + "options": { + "jestConfig": "apps/react-storybook/jest.config.ts", + "passWithNoTests": true + }, + "configurations": { + "ci": { + "ci": true, + "codeCoverage": true + } + } + }, + "serve-static": { + "executor": "@nrwl/web:file-server", + "defaultConfiguration": "development", + "options": { + "buildTarget": "react-storybook:build", + "port": 4200 + }, + "configurations": { + "development": { + "buildTarget": "react-storybook:build:development" + }, + "production": { + "buildTarget": "react-storybook:build:production" + } + } + }, + "storybook": { + "executor": "@nrwl/storybook:storybook", + "options": { + "uiFramework": "@storybook/react", + "port": 4400, + "configDir": "apps/react-storybook/.storybook" + }, + "configurations": { + "ci": { + "quiet": true + } + } + }, + "build-storybook": { + "executor": "@nrwl/storybook:build", + "outputs": ["{options.outputDir}"], + "options": { + "uiFramework": "@storybook/react", + "outputDir": "dist/storybook/react-storybook", + "configDir": "apps/react-storybook/.storybook" + }, + "configurations": { + "ci": { + "quiet": true + } + } + } + }, + "tags": [] +} diff --git a/apps/react-storybook/src/app/RemoteButton.stories.tsx b/apps/react-storybook/src/app/RemoteButton.stories.tsx new file mode 100644 index 00000000000..271e41b3d5e --- /dev/null +++ b/apps/react-storybook/src/app/RemoteButton.stories.tsx @@ -0,0 +1,33 @@ +import React, { Suspense } from 'react'; +import { Meta, Story } from '@storybook/react'; + +// @ts-ignore +const LazyButton = React.lazy(() => import('react-remote-ui/Button')); + +const Button = (props: any) => ( + Please wait...

}> + +
+); + +export default { + title: 'Remote/Button', + component: Button, + argTypes: { + variant: { control: 'select', options: ['primary', 'secondary'] }, + }, +} as Meta; + +const Template: Story = (args) =>