next.js - 模块联合或微前端在 Next js 版本 12.2.0 中不起作用

标签 next.js micro-frontend webpack-module-federation

我按照以下步骤在下一个 js 中实现了模块联合。

  1. 在存储库 cm-insurance-web 中的 src/node/components 文件夹中创建一个组件 Insurance_Detail.tsx,该组件将被公开。下面是 next.config.js 文件。
const assetPrefix = '/jobs-assets';
const nextConfig = {
  assetPrefix,
  env: {
    assetPrefix
  },
  experimental: {
    images: {
      unoptimized: true
    }
  },
  reactStrictMode: true,
  webpack5: true,
  srcDir: 'src/node/',
  //distDir: 'build',
  webpack: (config, options) => { // webpack configurations
    config.plugins.push(
        new options.webpack.container.ModuleFederationPlugin({
          name:"InsuranceA",
          filename: "static/chunks/pages/cm_insurance_web.js", // remote file name which will used later
          remoteType: "var",
          exposes: { // expose all component here.
            **"./InsuranceDetail": "./components/Insurance_Details.tsx"**
          },
          shared: [
            {
              react: {
                eager: true,
                singleton: true,
                requiredVersion: false,
              }
            },
            {
              "react-dom": {
                eager: true,
                singleton: true,
                requiredVersion: false,
              }
            },
          ]
        })
    )
      config.cache = false;
    config.output.publicPath = 'http://localhost:3000/_next/';
    return config
  }
}

module.exports = nextConfig
  1. 当我们使用命令 npm run build 构建 repo cm-insurance-web 时,我们可以看到在 src/node/.next/static/chunks/pages/cm_insurance_web.js 中创建了 javascript 文件。这个项目 repo 在本地主机的 3000 端口上运行。

  2. 现在需要在其他存储库中使用此 javascript,比如 cm-job-board-web。让我们创建消费者应用程序。下面是它的 next.config.js 文件

/** @type {import('next').NextConfig} */
const assetPrefix = '/jobs-assets';
const path = require('path');
const nextConfig = {
  assetPrefix,
  env: {
    assetPrefix
  },
  basePath: '/search-jobs',
  experimental: {
    images: {
      unoptimized: true
    }
  },
  reactStrictMode: true,
  srcDir: 'src/node/',
  webpack: (config, options) => {
    config.plugins.push(
        new options.webpack.container.ModuleFederationPlugin({
          name:"jobboardWeb",
          filename: "static/chunks/cm_job_board_web.js",
          remoteType: "var",
          remotes: {
              InsuranceA: JSON.stringify('InsuranceA@http://localhost:3000/jobs-assets/_next/static/chunks/pages/cm_insurance_web.js')
          },exposes: {},
            shared: [
                {
                    react: {
                        eager: true,
                        singleton: true,
                        requiredVersion: false,
                    }
                },
                {
                    "react-dom": {
                        eager: true,
                        singleton: true,
                        requiredVersion: false,
                    }
                },
            ]
        })
    )
      config.cache = false;
    return config
  },
  webpack5: true
}

module.exports = nextConfig
  1. 在consumer app的_app.tsx文件中添加script标签如下:
import { AppProps } from "next/app";
import "bootstrap/dist/css/bootstrap.css";
import "../styles/globals.scss";
import Layout from "../components/layout";
import { persistor, store } from "../store/store";
import { Provider } from "react-redux";
import { PersistGate } from "redux-persist/integration/react";
import Authentication from "../config/auth.gaurd";
import Head from "next/head";
import React from "react";
import Script from "next/script";

function MyApp({ Component, pageProps }: AppProps) {
  return (
    <Layout>
        <>
            <Script src="http://localhost:3000/jobs-assets/_next/static/chunks/pages/cm_insurance_web.js" />
            <Head>
                <link rel="preconnect" href="https://fonts.googleapis.com"/>
                <link rel="preconnect" href="https://fonts.gstatic.com"/>
                <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=IBM+Plex+Sans:wght@100;200;300;400;500;600;700&display=swap"/>
                <link rel="shortcut icon" href="/favicon2.ico"/>
                <title>Jobboard Search</title>
            </Head>
            <Script id="gtm-script" strategy="afterInteractive">
                {`(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
                    new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
                    j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
                    'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
                    })(window,document,'script','dataLayer','GTM-TKJH8RR');`
                }
            </Script>
            <Provider store={store}>
                <PersistGate loading={null} persistor={persistor}>
                    <Authentication>
                        <noscript dangerouslySetInnerHTML={{ __html:
                            `<iframe src="https://www.googletagmanager.com/ns.html?id=GTM-TKJH8RR"
                            height="0" width="0" style="display:none;visibility:hidden"></iframe>
                            `}}>
                        </noscript>
                        <Component {...pageProps} />
                    </Authentication>
                </PersistGate>
            </Provider>
        </>
    </Layout>
  );
}

export default MyApp;
  1. 让我们将该模块导入 index.tsx 文件并使用它。
import {NextPage} from "next";
import React, {lazy, Suspense, useState} from "react";
import dynamic from 'next/dynamic'


const InsuranceDetail2 = dynamic(() => import(('InsuranceA/InsuranceDetail')), {
    ssr: false
}) as NextPage;

const Insurance: NextPage = ({}: any) => {

    return (

            <InsuranceDetail2 />

    )
}


export default Insurance

完成上述步骤后,我能够看到远程 js 文件正在浏览器的网络选项卡中加载,但远程组件未呈现并出现空白页面。

Please find attached screenshot

如果我在这里遗漏了什么,请告诉我。我从下面的链接中获取了引用。

  1. https://blog.logrocket.com/micro-frontend-react-next-js/
  2. https://blog.logrocket.com/building-micro-frontends-webpacks-module-federation/
  3. https://dev.to/omher/building-react-app-with-module-federation-and-nextjsreact-1pkh

最佳答案

安装 nextjs-mf ⚠️ 注意:要使应用程序使用 Module Federation 功能,您需要访问 https://app.privjs.com/package?pkg=@module-federation/nextjs-mf[[nextjs-ssr^]目前需要付费许可的插件!

要安装该工具,我们需要使用 npm 登录 [PrivJs}(https://privjs.com/^),为此,请运行以下命令:

npm 登录 --registry https://r.privjs.com

完成此操作后,包含您的凭据的文件将保存在 ~/.npmrc 中。现在您可以使用以下命令安装 nextjs-mf:

npm install @module-federation/nextjs-mf --registry https://r.privjs.com

所以模块联合是下一个js中的付费模块,在付费模块的帮助下,我能够实现它。

  1. 保险模块的next.config.js。
/** @type {import('next').NextConfig} */
const NextFederationPlugin = require('@module-federation/nextjs-mf');
const assetPrefix = '/jobs-assets';
const nextConfig = {
  assetPrefix,
  env: {
    assetPrefix
  },
  reactStrictMode: true,
  webpack5: true,
  srcDir: 'src/node/',
  //distDir: 'build',
  webpack: (config, options) => { // webpack configurations
      if (!options.isServer) {
          config.plugins.push(
              new NextFederationPlugin({
                  name: "insurancea",
                  filename: "static/chunks/pages/cm_insurance_web.js", // remote file name which will used later
                  exposes: { // expose all component here.
                      "./insurancedetail": "./components/Insurance_Details.tsx"
                  },
                  shared:
                      {
                          react: {
                              singleton: true,
                              requiredVersion: false,
                          }
                      }
              }),
          );
      }
      return config
  }
};

module.exports = nextConfig

  1. 在 package.json 中添加模块联合的依赖。
"dependencies": {

 "@module-federation/nextjs-mf": "^5.9.2",
}
  1. 在同一保险模块的 _app.tsx 文件中添加导入。
import '@module-federation/nextjs-mf/src/include-defaults';

这就是暴露组件

  1. 现在在 next.config.js 中为远程组件(消费者应用程序 - cm-job-board-web)更新它
/** @type {import('next').NextConfig} */
const NextFederationPlugin = require('@module-federation/nextjs-mf');
const assetPrefix = '/jobs-assets';
const path = require('path');
const nextConfig = {
  assetPrefix,
  env: {
    assetPrefix
  },
  basePath: '/search-jobs',
  reactStrictMode: true,
  srcDir: 'src/node/',
  webpack: (config, options) => {
      if (!options.isServer) {
          config.plugins.push(
              new NextFederationPlugin({
                  name: "jobboardWeb",
                  filename: "static/chunks/cm_job_board_web.js",
                  remotes: {
                      //  cm_insurance_web: options.isServer ? 'http://localhost:3000/jobs-assets/_next/static/chunks/cm_insurance_web.js' : 'fe1'
                      insurancea: 'insurancea@http://localhost:3000/jobs-assets/_next/static/chunks/pages/cm_insurance_web.js'
                  }, exposes: {},
                  shared: {}
              }),
          );
      }
    return config
  },
  webpack5: true
};

module.exports = nextConfig

  1. 在消费者应用程序的 package.json 中添加模块联合的依赖。
"dependencies": {

 "@module-federation/nextjs-mf": "^5.9.2",
}
  1. 在消费者应用程序的 _app.tsx 文件中添加导入。
import '@module-federation/nextjs-mf/src/include-defaults';
  1. 最后将该模块导入 index.tsx 文件并在消费者应用程序中使用它。
import { Suspense } from 'react'
import React from 'react'
import dynamic from 'next/dynamic'

const DynamicComponent4 = dynamic(
    () => import('insurancea/insurancedetail'),
    { loading: () => <p>Loading caused by client page transition ...</p>, ssr: false }
)


export default function Insurance() {
    return (
        <div>

                <DynamicComponent4 />

        </div>
    )
}

就是这样。

关于next.js - 模块联合或微前端在 Next js 版本 12.2.0 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73986638/

相关文章:

javascript - 在不刷新页面的情况下更改 URl NEXT.JS

javascript - NextJs 链接到另一个页面,然后使用 : react-scroll 滚动

frameworks - 框架不可知论是什么意思?

Cypress 模拟模块联邦微前端

javascript - Webpack 模块联合不适用于急切的共享库

reactjs - Webpack 模块联邦延迟加载 remoteEntry.js

Angular微前端无限刷新

javascript - 将 unicode 转义添加到动态字符串值

angular - 使用 Angular 创建微前端的最佳方法是什么?

javascript - 使用 getServerSideProps next :js 部署后发生内部服务器错误 500