首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >模块联盟或微前端在下一个js版本12.2.0中不起作用

模块联盟或微前端在下一个js版本12.2.0中不起作用
EN

Stack Overflow用户
提问于 2022-10-07 11:40:28
回答 1查看 428关注 0票数 1

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

  1. 在src/节点/components文件夹中的存储库cm-保险-web中创建一个组件Insurance_Detail.tsx,该组件将被公开。下面是next.config.js文件。
代码语言:javascript
运行
复制
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运行build构建回购cm保险web时,我们可以看到javascript文件是在src/node/.next/static/chunks/pages/cm_insurance_web.js.中创建的。该项目正在本地主机上的3000端口上运行。
  2. 现在需要在其他存储库中使用这个javascript,比如说cm作业板-web。让我们创建消费者应用程序。下面是它的next.config.js文件
代码语言:javascript
运行
复制
/** @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. 在消费应用程序的_app.tsx文件中添加脚本标记如下:
代码语言:javascript
运行
复制
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文件并使用它。
代码语言:javascript
运行
复制
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文件正在加载到浏览器的网络选项卡中,但是远程组件并没有被呈现并获得空白页。

请查找附呈的截图

如果我遗漏了什么,请告诉我。我从下面的链接中获得了参考。

  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
EN

Stack Overflow用户

回答已采纳

发布于 2022-10-12 12:48:17

安装nextjs⚠️注意:要使应用程序与模块联邦功能一起工作,您需要访问[https://app.privjs.com/package?pkg=@module-federation/nextjs-mf[[nextjs-ssr^]](https://app.privjs.com/package?pkg=@module-federation/nextjs-mf%5B%5Bnextjs-ssr%5E%5D)插件,该插件目前需要付费许可!

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

npm登录--注册表https://r.privjs.com

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

npm安装@模块-联邦/nextjs注册表https://r.privjs.com

因此,在下一个js中,模块联邦就是付费模块,在付费模块的帮助下,我能够实现它。

  1. 保险模块的next.config.js。
代码语言:javascript
运行
复制
/** @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中添加模块联邦的依赖关系。
代码语言:javascript
运行
复制
"dependencies": {

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

这就是公开组件的原因

  1. 现在,在next.config.js中为远程组件(消费应用程序-cm-作业板-web)更新它。
代码语言:javascript
运行
复制
/** @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中添加模块联邦的依赖关系。
代码语言:javascript
运行
复制
"dependencies": {

 "@module-federation/nextjs-mf": "^5.9.2",
}
  1. 在消费应用程序的_app.tsx文件中添加导入。
代码语言:javascript
运行
复制
import '@module-federation/nextjs-mf/src/include-defaults';
  1. 最后,将该模块导入到index.tsx文件中,并在用户应用程序中使用。
代码语言:javascript
运行
复制
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>
    )
}

就这样。

票数 0
EN
查看全部 1 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73986638

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档