游戏王的故事

基于create-react-app的多页面配置

2021-11-26  本文已影响0人  SwiftBirds

代码仓库:

gitee仓库

GitHub仓库

1. 创建项目

npx create-react-app ProjectName --template typescript

Untitled.png

2. 多页面应用配置

2.1 弹出webpack配置

由于create-react-app隐藏了webpack配置,因此首先需要将该项目的webpack配置暴露出来。运行如下命令

npm run eject

💡 运行该命令之前需要将修改的代码提交到git!

2.2 创建多页面文件

假设该多页面应用程序包括前台展示页面和后台管理页面。则在src下创建两个文件夹home和admin分别对应两个页面

import React from "react";
import ReactDOM from "react-dom";

ReactDOM.render(
  <React.StrictMode>
    <div>前台页面主入口</div>
  </React.StrictMode>,
  document.getElementById("root")
);

import React from "react";
import ReactDOM from "react-dom";

ReactDOM.render(
  <React.StrictMode>
    <div>后台页面主入口</div>
  </React.StrictMode>,
  document.getElementById("root")
);

然后对应这两个页面还需要创建对应的html模板

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="theme-color" content="#000000" />
    <meta
      name="description"
      content="Web site created using create-react-app"
    />
    <link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
    <link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
    <title>前台展示页面</title>
  </head>
  <body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>
  </body>
</html>

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="theme-color" content="#000000" />
    <meta
      name="description"
      content="Web site created using create-react-app"
    />
    <link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
    <link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
    <title>后台管理页面</title>
  </head>
  <body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>
  </body>
</html>

进行上述一系列的操作后,文件结构如下图所示

Untitled (1).png

2.3 修改打包相关配置

  1. 首先修改文件路径映射

来到config/paths.js文件下,在module.exports中,修改appIndexJs的文件路径,添加adminHtml和adminIndexJs的文件路径

module.exports = {
  dotenv: resolveApp('.env'),
  appPath: resolveApp('.'),
  appBuild: resolveApp(buildPath),
  appPublic: resolveApp('public'),
  appHtml: resolveApp('public/index.html'),
  appIndexJs: resolveModule(resolveApp, 'src/home/index'),
  adminHtml: resolveApp('public/admin.html'),
  adminIndexJs: resolveModule(resolveApp, 'src/admin/index'),
  appPackageJson: resolveApp('package.json'),
  appSrc: resolveApp('src'),
  appTsConfig: resolveApp('tsconfig.json'),
  appJsConfig: resolveApp('jsconfig.json'),
  yarnLockFile: resolveApp('yarn.lock'),
  testsSetup: resolveModule(resolveApp, 'src/setupTests'),
  proxySetup: resolveApp('src/setupProxy.js'),
  appNodeModules: resolveApp('node_modules'),
  swSrc: resolveModule(resolveApp, 'src/service-worker'),
  publicUrlOrPath
}

  1. 修改webpack中的配置

来到config/webpack.config.js文件中。

entry: {
  home: isEnvDevelopment && !shouldUseReactRefresh ? [ webpackDevClientEntry, paths.appIndexJs, ] : paths.appIndexJs,
  admin: isEnvDevelopment && !shouldUseReactRefresh ? [ webpackDevClientEntry, paths.adminIndexJs ] : paths.adminIndexJs,
},

output: {
  /** 其余代码不动 */
  filename: isEnvProduction
    ? 'static/js/[name].[contenthash:8].js'
    : isEnvDevelopment && 'static/js/[name].bundle.js'
  futureEmitAssets: true,
  chunkFilename: isEnvProduction
    ? 'static/js/*[name].[contenthash:8].chunk.js*'
    : isEnvDevelopment && 'static/js/[name].chunk.js',
},

plugins: [
  /** 其余代码不动 */
  new HtmlWebpackPlugin(
    Object.assign(
      {},
      {
        inject: true,
        chunks: ['home'],
        template: paths.appHtml,
        filename: 'index.html'
      },
      isEnvProduction
        ? {
            minify: {
              removeComments: true,
              collapseWhitespace: true,
              removeRedundantAttributes: true,
              useShortDoctype: true,
              removeEmptyAttributes: true,
              removeStyleLinkTypeAttributes: true,
              keepClosingSlash: true,
              minifyJS: true,
              minifyCSS: true,
              minifyURLs: true,
            },
          }
        : undefined
    )
  ),
  new HtmlWebpackPlugin(
    Object.assign(
      {},
      {
        inject: true,
        chunks: ['admin'],
        template: paths.adminHtml,
        filename: 'admin.html'
      },
      isEnvProduction
        ? {
            minify: {
              removeComments: true,
              collapseWhitespace: true,
              removeRedundantAttributes: true,
              useShortDoctype: true,
              removeEmptyAttributes: true,
              removeStyleLinkTypeAttributes: true,
              keepClosingSlash: true,
              minifyJS: true,
              minifyCSS: true,
              minifyURLs: true,
            },
          }
        : undefined
    )
  ),
    /** 注释掉ManifestPlugin插件配置 */
    // new ManifestPlugin({
    //   fileName: 'asset-manifest.json',
    //   publicPath: paths.publicUrlOrPath,
    //   generate: (seed, files, entrypoints) => {
    //     const manifestFiles = files.reduce((manifest, file) => {
    //       manifest[file.name] = file.path;
    //       return manifest;
    //     }, seed);
    //     const entrypointFiles = entrypoints.main.filter(
    //       fileName => !fileName.endsWith('.map')
    //     );

    //     return {
    //       files: manifestFiles,
    //       entrypoints: entrypointFiles,
    //     };
    //   },
    // }),
]

💡 HtmlWebpackPlugin这个plugin曝光率很高,他主要有两个作用: (1)为html文件中引入的外部资源如script、link动态添加每次compile后的hash,防止引用缓存的外部文件问题;(2)可以生成创建html入口文件,比如单页面可以生成一个html文件入口,配置N个html-webpack-plugin可以生成N个页面入口

2.4 修改启动脚本配置

在启动脚本代码里,他会检查html模板文件、多页面的入口文件的路径映射是否存在。由于修改了路径映射文件,因此也需要对启动脚本代码进行修改。

分别来到scripts/build.jsscripts/start.js文件。找到如下代码并进行修改。

// 修改前的代码
if (!checkRequiredFiles([paths.appHtml, paths.appIndexJs])) {
  process.exit(1);
}

// 修改后的代码
if (!checkRequiredFiles([paths.appHtml, paths.appIndexJs, paths.adminHtml, paths.adminIndexJs])) {
  process.exit(1);
}

至此,多页面的相关配置已修改完毕。

3. 多页面结果查看

3.1 查看页面

运行如下命令,重新启动项目

npm start

在控制台输入localhost:3000(或localhost:3000/index.html),页面展示的结果如下所示:

Untitled (2).png

在控制台输入localhost:3000/admin.html,页面展示的结果如下所示:

Untitled (3).png

页面结果符合预期

3.2 总结

配置多页面应用的步骤如下:

  1. 在public下创建多个html模板,每个html模板对应一个页面应用。如果页面模板没有差别的话,可以只创建一个;
  2. 在src下新建多个文件夹,每个文件夹对应一个页面应用。在每个文件夹下建立一个index.tsx作为该页面应用的入口文件,在该文件中,将react挂载到html模板中的根节点中去;
  3. 修改config/paths.js文件下的路径映射,将多页面的html模板和入口文件添加到路径映射中去;
  4. 配置webpack的entry,为每个多页面应用起个名字作为key,将入口文件作为value;
  5. 配置webpack的output,将打包后的文件名改为[name].bundle.js ,其中name为entry中的key;
  6. 配置webpack的plugin,有多少个页面应用就创建多少个HtmlWebpackPlugin,并对其配置对应的html模板和打包后的文件名(即entry中的key)
  7. 修改scripts目录下的文件。更改校验文件是否存在的代码,将paths.js中新增的路径映射添加到判断条件中
  8. 重启项目,检查结果。
上一篇 下一篇

猜你喜欢

热点阅读