@module-federation/nextjs-mf 8.0.1-4 → 8.1.0-canary.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md DELETED
@@ -1,471 +0,0 @@
1
- <div align="center">
2
- <!-- for version -->
3
- <img src="https://img.shields.io/npm/v/@module-federation/nextjs-mf" alt="version" >
4
- <img src="https://img.shields.io/npm/l/@module-federation/nextjs-mf.svg?" alt="license" >
5
- <!-- for downloads -->
6
- <img src="https://img.shields.io/npm/dt/@module-federation/nextjs-mf" alt="downloads">
7
- </div>
8
-
9
- # Module Federation For Next.js
10
-
11
- This plugin enables Module Federation on Next.js
12
-
13
- ## Supports
14
-
15
- - next ^13 || ^12(?)
16
- - SSR included!
17
-
18
- I highly recommend referencing this application which takes advantage of the best capabilities:
19
- https://github.com/module-federation/module-federation-examples
20
-
21
- ## This project supports federated SSR
22
-
23
- # We are building a micro-frontend ecosystem!
24
-
25
- While NextFederationPlugin "works", Next.js is staunchly opposed to the technology and Next is very difficult to support.
26
-
27
- This plugin attempts to make the experience as seamless as possible, but it is not perfect.
28
-
29
- We are building a micro-frontend ecosystem that is much more powerful than Next.js, built to support micro-frontends from the ground up.
30
-
31
- **If Federation is a big enabler for your teams and projects, please consider using our ecosystem thats designed for it**
32
-
33
- | [Rspack](https://github.com/web-infra-dev/rspack) | <a href="https://github.com/web-infra-dev/rspack" target="blank"><img src="https://lf3-static.bytednsdoc.com/obj/eden-cn/zq-uylkvT/ljhwZthlaukjlkulzlp/Rspack-1850.png" width="400" /></a> |
34
- | :-----------------------------------------------------: | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------: |
35
- | [Modern.js](https://github.com/web-infra-dev/modern.js) | <a href="https://github.com/web-infra-dev/modern.js" target="blank"><img src="https://lf3-static.bytednsdoc.com/obj/eden-cn/zq-uylkvT/ljhwZthlaukjlkulzlp/Modern-0550.png" width="400" /></a> |
36
- | [Garfish](https://github.com/web-infra-dev/garfish) | <a href="https://github.com/web-infra-dev/garfish" target="blank"><img src="https://lf3-static.bytednsdoc.com/obj/eden-cn/zq-uylkvT/ljhwZthlaukjlkulzlp/Garfish-1630.png" width="400" /></a> |
37
- | [Oxc](https://github.com/web-infra-dev/oxc) | <a href="https://github.com/web-infra-dev/oxc" target="blank"><img src="https://lf3-static.bytednsdoc.com/obj/eden-cn/zq-uylkvT/ljhwZthlaukjlkulzlp/Oxc-0724.png" width="400" /></a> |
38
-
39
- ## Whats shared by default?
40
-
41
- Under the hood we share some next internals automatically
42
- You do not need to share these packages, sharing next internals yourself will cause errors.
43
-
44
- <details>
45
- <summary> See DEFAULT_SHARE_SCOPE:</summary>
46
-
47
- ```ts
48
- export const DEFAULT_SHARE_SCOPE: SharedObject = {
49
- 'next/dynamic': {
50
- eager: false,
51
- requiredVersion: false,
52
- singleton: true,
53
- import: undefined,
54
- },
55
- 'next/head': {
56
- eager: false,
57
- requiredVersion: false,
58
- singleton: true,
59
- import: undefined,
60
- },
61
- 'next/link': {
62
- eager: true,
63
- requiredVersion: false,
64
- singleton: true,
65
- import: undefined,
66
- },
67
- 'next/router': {
68
- requiredVersion: false,
69
- singleton: true,
70
- import: false,
71
- eager: false,
72
- },
73
- 'next/script': {
74
- requiredVersion: false,
75
- singleton: true,
76
- import: undefined,
77
- eager: false,
78
- },
79
- react: {
80
- singleton: true,
81
- requiredVersion: false,
82
- eager: false,
83
- import: false,
84
- },
85
- 'react-dom': {
86
- singleton: true,
87
- requiredVersion: false,
88
- eager: false,
89
- import: false,
90
- },
91
- 'react/jsx-dev-runtime': {
92
- singleton: true,
93
- requiredVersion: false,
94
- import: undefined,
95
- eager: false,
96
- },
97
- 'react/jsx-runtime': {
98
- singleton: true,
99
- requiredVersion: false,
100
- eager: false,
101
- import: false,
102
- },
103
- 'styled-jsx': {
104
- requiredVersion: false,
105
- singleton: true,
106
- import: undefined,
107
- eager: false,
108
- },
109
- 'styled-jsx/style': {
110
- requiredVersion: false,
111
- singleton: true,
112
- import: undefined,
113
- eager: false,
114
- },
115
- };
116
- ```
117
-
118
- </details>
119
-
120
-
121
- ## Requirement
122
-
123
- I set `process.env.NEXT_PRIVATE_LOCAL_WEBPACK = 'true'` inside this plugin, but its best if its set in env or command line export.
124
-
125
- "Local Webpack" means you must have webpack installed as a dependency, and next will not use its bundled copy of webpack which cannot be used as i need access to all of webpack internals
126
-
127
- - `NEXT_PRIVATE_LOCAL_WEBPACK=true next dev` or `next build`
128
- - `npm install webpack`
129
-
130
-
131
- ## Usage
132
-
133
- ```js
134
- import React, { lazy } from 'react';
135
- const SampleComponent = lazy(() => import('next2/sampleComponent'));
136
- ```
137
-
138
- To avoid hydration errors, use `React.lazy` instead of `next/dynamic` for lazy loading federated components.
139
-
140
- #### See the implementation here: https://github.com/module-federation/module-federation-examples/tree/master/nextjs-v13/home/pages
141
-
142
- With async boundary installed at the page level. You can then do the following
143
-
144
- ```js
145
- const SomeHook = require('next2/someHook');
146
- import SomeComponent from 'next2/someComponent';
147
- ```
148
-
149
- ## Demo
150
-
151
- You can see it in action here: https://github.com/module-federation/module-federation-examples/tree/master/nextjs-ssr
152
-
153
- ## Options
154
-
155
- This plugin works exactly like ModuleFederationPlugin, use it as you'd normally.
156
- Note that we already share react and next stuff for you automatically.
157
-
158
- Also NextFederationPlugin has own optional argument `extraOptions` where you can unlock additional features of this plugin:
159
-
160
- ```js
161
- new NextFederationPlugin({
162
- name: '',
163
- filename: '',
164
- remotes: {},
165
- exposes: {},
166
- shared: {},
167
- extraOptions: {
168
- debug: boolean, // `false` by default
169
- exposePages: boolean, // `false` by default
170
- enableImageLoaderFix: boolean, // `false` by default
171
- enableUrlLoaderFix: boolean, // `false` by default
172
- skipSharingNextInternals: boolean, // `false` by default
173
- },
174
- });
175
- ```
176
-
177
- - `debug` – enables debug mode. It will print additional information about what is going on under the hood.
178
- - `exposePages` – exposes automatically all nextjs pages for you and theirs `./pages-map`.
179
- - `enableImageLoaderFix` – adds public hostname to all assets bundled by `nextjs-image-loader`. So if you serve remoteEntry from `http://example.com` then all bundled assets will get this hostname in runtime. It's something like Base URL in HTML but for federated modules.
180
- - `enableUrlLoaderFix` – adds public hostname to all assets bundled by `url-loader`.
181
- - `skipSharingNextInternals` – disables sharing of next internals. You can use it if you want to share next internals yourself or want to use this plugin on non next applications
182
-
183
- ## Demo
184
-
185
- You can see it in action here: https://github.com/module-federation/module-federation-examples/pull/2147
186
-
187
- ## Implementing the Plugin
188
-
189
- 1. Use `NextFederationPlugin` in your `next.config.js` of the app that you wish to expose modules from. We'll call this "next2".
190
-
191
- ```js
192
- // next.config.js
193
- // either from default
194
- const NextFederationPlugin = require('@module-federation/nextjs-mf');
195
-
196
- module.exports = {
197
- webpack(config, options) {
198
- const { isServer } = options;
199
- config.plugins.push(
200
- new NextFederationPlugin({
201
- name: 'next2',
202
- remotes: {
203
- next1: `next1@http://localhost:3001/_next/static/${isServer ? 'ssr' : 'chunks'}/remoteEntry.js`,
204
- },
205
- filename: 'static/chunks/remoteEntry.js',
206
- exposes: {
207
- './title': './components/exposedTitle.js',
208
- './checkout': './pages/checkout',
209
- },
210
- shared: {
211
- // whatever else
212
- },
213
- }),
214
- );
215
-
216
- return config;
217
- },
218
- };
219
- ```
220
-
221
- ```js
222
- // next.config.js
223
-
224
- const NextFederationPlugin = require('@module-federation/nextjs-mf');
225
-
226
- module.exports = {
227
- webpack(config, options) {
228
- const { isServer } = options;
229
- config.plugins.push(
230
- new NextFederationPlugin({
231
- name: 'next1',
232
- remotes: {
233
- next2: `next2@http://localhost:3000/_next/static/${isServer ? 'ssr' : 'chunks'}/remoteEntry.js`,
234
- },
235
- }),
236
- );
237
-
238
- return config;
239
- },
240
- };
241
- ```
242
-
243
- 4. Use react.lazy, low level api, or require/import from to import remotes.
244
-
245
- ```js
246
- import React, { lazy } from 'react';
247
-
248
- const SampleComponent = lazy(() =>
249
- window.next2.get('./sampleComponent').then((factory) => {
250
- return { default: factory() };
251
- }),
252
- );
253
-
254
- // or
255
-
256
- const SampleComponent = lazy(() => import('next2/sampleComponent'));
257
-
258
- //or
259
-
260
- import Sample from 'next2/sampleComponent';
261
- ```
262
-
263
- ## Delegate modules
264
-
265
- Delegated modules are now a standard feature in module federation, giving you the ability to manage the loading procedure of remote modules via an internally bundled file by webpack. This is facilitated by exporting a promise in the delegate file that resolves to a remote/container interface.
266
-
267
- A container interface represents the fundamental `{get, init}` API that remote entries present to a consuming app. Within the browser, a remote container could be `window.app1`, and in Node, it could be `globalThis.__remote_scope__.app1`.
268
-
269
- Implementing a method for script loading in the delegate file is necessary for the utilization of delegated modules. Although the built-in `__webpack_require__.l` method of webpack is a prevalent method, any method is suitable. This method is made available to the runtime and is identical to the method webpack employs internally to load remotes.
270
-
271
- Please note that using delegated modules demands a minimum version of `6.1.x` across all applications, given that consumers must be capable of handling the new container interface.
272
-
273
- Here's a sample usage of a delegated module with `__webpack_require__.l`:
274
-
275
- <details>
276
- <summary>See Example: (click) </summary>
277
- In this example, the delegated module exports a promise that loads the remote entry script located at "http://localhost:3000/_next/static/chunks/remoteEntry.js",
278
- based on the `__resourceQuery` variable set by webpack at runtime.
279
- If an error surfaces while loading the script, a unique error object is generated, and the promise is rejected with this error.
280
-
281
- ```js
282
- //next.config.js
283
- const { createDelegatedModule } = require('@module-federation/nextjs-mf/utilities');
284
- const remotes = {
285
- checkout: createDelegatedModule(require.resolve('./remote-delegate.js'), {
286
- remote: `checkout@http://localhost:3002/_next/static/${isServer ? 'ssr' : 'chunks'}/remoteEntry.js`,
287
- otherParam: 'testing',
288
- }),
289
- };
290
-
291
- //remote-delegate.js
292
- // Delegates must utilize module.exports, not export default - this is due to a webpack constraint
293
- // ALL imports MUST BE dynamic imports in here like import()
294
- module.exports = new Promise(async (resolve, reject) => {
295
- const { importDelegatedModule } = await import('@module-federation/nextjs-mf/importDelegatedModule');
296
- // eslint-disable-next-line no-undef
297
- const currentRequest = new URLSearchParams(__resourceQuery).get('remote');
298
- const [global, url] = currentRequest.split('@');
299
- importDelegatedModule({
300
- global,
301
- url: url + '?' + Date.now(),
302
- })
303
- .then((remote) => {
304
- resolve(remote);
305
- })
306
- .catch((err) => reject(err));
307
- });
308
- ```
309
-
310
- </details>
311
-
312
- In the `next.config.js` file, where remotes are configured in the module federation plugin,
313
- you can use the internal hint to tell webpack to use an internal file as the remote entry.
314
- This is done by replacing the typical global@url syntax with `internal ./path/to/module`.
315
-
316
- Webpack has several hint types:
317
-
318
- - `internal `
319
- - `promise `
320
- - `import `
321
- - `external `
322
- - `script `
323
-
324
- The `global@url` syntax is actually script hint: `script global@url`
325
-
326
- If you want to use the same file for handling all remote entries, you can pass information to the delegate module using query parameters.
327
- Webpack will pass the query parameters to the module as a string, this is known as `__resourceQuery`.
328
- It allows you to pass information to the delegate module, so it knows what webpack is currently asking for.
329
-
330
- You can use query parameters to pass data to a module, webpack will pass the query parameters to the module as a string.
331
-
332
- For more information on `__resourceQuery` visit: https://webpack.js.org/api/module-variables/#__resourcequery-webpack-specific.
333
-
334
- ```js
335
- // next.config.js
336
- // its advised you use {createDelegatedModule} from @module-federation/utilities (re-exported as @module-federation/nextjs-mf/utilities) instead of manually creating the delegate module
337
- const remotes = {
338
- // pass pointer to remote-delegate, pass delegate remote name as query param,
339
- // at runtime webpack will pass this as __resourceQuery
340
- shop: `internal ./remote-delegate.js?remote=shop@http://localhost:3001/_next/static/${isServer ? 'ssr' : 'chunks'}/remoteEntry.js`,
341
- checkout: `internal ./remote-delegate.js?remote=checkout@http://localhost:3002/_next/static/${isServer ? 'ssr' : 'chunks'}/remoteEntry.js`,
342
- };
343
- ```
344
-
345
- #### Expand below to see a full example:
346
-
347
- <details>
348
- <summary>See Full configuration with no helpers: (click) </summary>
349
-
350
- ```js
351
- // next.config.js
352
-
353
- const remotes = {
354
- // pass pointer to remote-delegate, pass deletae remote name as query param,
355
- // at runtime webpack will pass this as __resourceQuery
356
- shop: `internal ./remote-delegate.js?remote=shop@http://localhost:3001/_next/static/${isServer ? 'ssr' : 'chunks'}/remoteEntry.js`,
357
- checkout: `internal ./remote-delegate.js?remote=checkout@http://localhost:3002/_next/static/${isServer ? 'ssr' : 'chunks'}/remoteEntry.js`,
358
- };
359
-
360
- // remote-delegate.js
361
- module.exports = new Promise((resolve, reject) => {
362
- // some node specific for NodeFederation
363
- if (!globalThis.__remote_scope__) {
364
- // create a global scope for container, similar to how remotes are set on window in the browser
365
- globalThis.__remote_scope__ = {
366
- _config: {},
367
- };
368
- }
369
- console.log('Delegate being called for', __resourceQuery);
370
- // get "remote" off resource query, returns url@global
371
- const currentRequest = new URLSearchParams(__resourceQuery).get('remote');
372
- // parse syntax
373
- const [containerGlobal, url] = currentRequest.split('@');
374
- // if node server, register the containers known origins
375
- if (typeof window === 'undefined') {
376
- globalThis.__remote_scope__._config[global] = url;
377
- }
378
- const __webpack_error__ = new Error();
379
- // if you use NodeFederationPlugin, ive build a server-side version of __webpack_require__.l, with the same api.
380
- // this is how module federation works on the server, i wrote server-side chunk loading.
381
- __webpack_require__.l(
382
- url,
383
- function (event) {
384
- // resolve promise with container, for browser env or node env.
385
- const container = typeof window === 'undefined' ? globalThis.__remote_scope__[containerGlobal] : window[containerGlobal];
386
- console.log('delegate resolving', container);
387
- if (typeof container !== 'undefined') return resolve(container);
388
- var realSrc = event && event.target && event.target.src;
389
- __webpack_error__.message = 'Loading script failed.\\n(' + event.message + ': ' + realSrc + ')';
390
- __webpack_error__.name = 'ScriptExternalLoadError';
391
- __webpack_error__.stack = event.stack;
392
- reject(__webpack_error__);
393
- },
394
- containerGlobal,
395
- );
396
- });
397
- ```
398
-
399
- </details>
400
-
401
- ## Utilities
402
-
403
- Ive added a util for dynamic chunk loading, in the event you need to load remote containers dynamically.
404
-
405
- **InjectScript**
406
-
407
- ```js
408
- import { injectScript } from '@module-federation/nextjs-mf/utils';
409
- // if i have remotes in my federation plugin, i can pass the name of the remote
410
- injectScript('home').then((remoteContainer) => {
411
- remoteContainer.get('./exposedModule');
412
- });
413
- // if i want to load a custom remote not known at build time.
414
-
415
- injectScript({
416
- global: 'home',
417
- url: 'http://somthing.com/remoteEntry.js',
418
- }).then((remoteContainer) => {
419
- remoteContainer.get('./exposedModule');
420
- });
421
- ```
422
-
423
- **revalidate**
424
-
425
- Enables hot reloading of node server (not client) in production.
426
- This is recommended, without it - servers will not be able to pull remote updates without a full restart.
427
-
428
- More info here: https://github.com/module-federation/nextjs-mf/tree/main/packages/node#utilities
429
-
430
- ```js
431
- // __document.js
432
-
433
- import { revalidate } from '@module-federation/nextjs-mf/utils';
434
- import Document, { Html, Head, Main, NextScript } from 'next/document';
435
- class MyDocument extends Document {
436
- static async getInitialProps(ctx) {
437
- const initialProps = await Document.getInitialProps(ctx);
438
-
439
- // can be any lifecycle or implementation you want
440
- ctx?.res?.on('finish', () => {
441
- revalidate().then((shouldUpdate) => {
442
- console.log('finished sending response', shouldUpdate);
443
- });
444
- });
445
-
446
- return initialProps;
447
- }
448
- render() {
449
- return (
450
- <Html>
451
- <Head />
452
- <body>
453
- <Main />
454
- <NextScript />
455
- </body>
456
- </Html>
457
- );
458
- }
459
- }
460
- ```
461
-
462
- ## For Express.js
463
-
464
- Hot reloading Express.js required additional steps: https://github.com/module-federation/universe/blob/main/packages/node/README.md
465
-
466
- ## Contact
467
-
468
- If you have any questions or need to report a bug
469
- <a href="https://twitter.com/ScriptedAlchemy"> Reach me on Twitter @ScriptedAlchemy</a>
470
-
471
- Or join this discussion thread: https://github.com/module-federation/module-federation-examples/discussions/978