create-react-app多页面配置

栏目: 服务器 · 发布时间: 6年前

使用 create-react-app 快速创建 react 项目

# terminal
# 在命令行中执行
npx create-react-app react-mpa
复制代码

使用 npm run eject 把webpack配置 喷出来

# terminal
# 打开 步骤1 中生成的react-mpa项目
cd react-mpa

# 执行 喷出配置的命令
npm run eject
复制代码

整理目录结构 并把多余的文件删除

create-react-app多页面配置

在src下新建 pages 目录 页面对应的路由 为index.js 的文件夹名字

index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>home</title>
  </head>
  <body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>
  </body>
</html>
复制代码

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import App from "~/App";

ReactDOM.render(<App />, document.getElementById('root'));
复制代码

App.js

import React from 'react';

function App() {
  return (
    <div className="App">
      <h1>index</h1>
    </div>
  );
}

export default App;
复制代码

修改 config/webpack.config.js 的配置

红线 标出被修改的属性

create-react-app多页面配置
return {
// ... 其他配置

// webpack js编译的入口文件 有多少个路由 就有多少个 入口js
// 莫慌 后续会用 函数 生成对应配置 不用手动添加
entry: {
  index: [
    isEnvDevelopment &&
      require.resolve('react-dev-utils/webpackHotDevClient'),
    `./src/pages/index/index.js`,
  ],
  home: [
    isEnvDevelopment &&
      require.resolve('react-dev-utils/webpackHotDevClient'),
    `./src/pages/home/index.js`,
  ],
  bathroom: [
    isEnvDevelopment &&
      require.resolve('react-dev-utils/webpackHotDevClient'),
    `./src/pages/bathroom/index.js`,
  ],
},

// 只改了两项 不知道为什么 默认的 [contenthash] 报错了,所以改成 [hash] 
output: {
  filename: isEnvProduction
    ? 'static/js/[name]/[name].[hash:8].js'
    : isEnvDevelopment && 'static/js/[name]/[name].[hash:8].js',
  chunkFilename: isEnvProduction
    ? 'static/js/[name]/[name].[hash:8].chunk.js'
    : isEnvDevelopment && 'static/js/[name]/[name].chunk.js',
},

// 添加了 ~ 映射 根目录的 src 文件
resolve: {
  alias: {
    'react-native': 'react-native-web',
    '~': path.resolve(__dirname, '../src')
  },
},

// 对应着 pages 的路由修改 有多少个路由 就有多少个 HtmlWebpackPlugin
// 莫慌 后续会用 函数 生成对应配置 不用手动添加
plugins: [
  new HtmlWebpackPlugin(
    Object.assign(
      {},
      {
        inject: true,
        template: `src/pages/index/index.html`,
        filename: `index/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,
        template: `src/pages/home/index.html`,
        filename: `home/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,
        template: `src/pages/home/bathroom/index.html`,
        filename: `home/bathroom/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
    )
  )
]
}

复制代码

修改 script/start.jsscript/build.js

// 两个文件都是一样的 把校验注释
// 这个校验作用是 在执行脚本前 检测 src/index.js 文件是否存在 
// 因为我们已经把入口文件改了 所以校验逻辑应该是 校验 pages 目录
// 不过可有可无 追求极致的可以自行添加
// if (!checkRequiredFiles([paths.appHtml, paths.appIndexJs])) {
//   process.exit(1);
// }
复制代码

好了 基础版配置完成 试着 运行一下吧

# terminal
npm start
复制代码

使用 函数 优化需要手动反复添加的配置项

修改的文件

create-react-app多页面配置

安装相关依赖

# terminal
npm i --save-dev glob
复制代码

mpaConfig.js

``javascript
const glob = require('glob')
const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin');

const paths = require('./paths')

/**
 * 获取多页面入口文件
 * @param {String} globPath 文件路径
 * @param {Boolean} isEnvDevelopment 是否为开发环境
 * @param {Boolean} isEnvProduction 是否为生产环境
 */
function getMpaConfig (appMpaSrc, isEnvDevelopment, isEnvProduction) {
  const globPath = `${appMpaSrc}/**/index.js`
  const moduleNameReg = /pages\/(.*)\//i
  return glob.sync(globPath).reduce((result, entry) => {
    // 获取模块名称
    const moduleName = moduleNameReg.exec(entry)[1]

    // 入口配置
    result.entry[moduleName] = [
      isEnvDevelopment &&
        require.resolve('react-dev-utils/webpackHotDevClient'),
      `./src/pages/${moduleName}/index.js`,
    ].filter(Boolean)

    // HtmlWebpackPlugin
    result.HtmlWebpackPlugin.push(new HtmlWebpackPlugin(
      Object.assign(
        {},
        {
          inject: true,
          template: `src/pages/${moduleName}/index.html`,
          filename: `${moduleName}/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
      )
    ))
    
    return result
  }, {
    entry: {},
    HtmlWebpackPlugin: []
  })
}

module.exports = {
  getMpaConfig
}
```
复制代码

webpack.config.js

// 在最上方 引入 mpaConfig
const { getMpaConfig } = require('./mpaConfig')

// 获取 多页面的配置
module.exports = function(webpackEnv) {
  const isEnvDevelopment = webpackEnv === 'development';
  const isEnvProduction = webpackEnv === 'production';
  const mpaConfig = getMpaConfig(paths.appMpaSrc, isEnvDevelopment, isEnvProduction)
  
  // ... other code
  return {
    entry: mpaConfig.entry,
    plugins: [
      // 把所有 HtmlWebpackPlugin 的配置删掉
      // 把 整理好的 HtmlWebpackPlugin配置展开
      ...mpaConfig.HtmlWebpackPlugin,
    ]
  }
}
复制代码

配置完成

  • 试着 运行 npm startnpm build

以上所述就是小编给大家介绍的《create-react-app多页面配置》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

复杂网络理论及其应用

复杂网络理论及其应用

汪小帆、李翔、陈关荣 / 清华大学出版社 / 2006 / 45.00元

国内首部复杂网络专著 【图书目录】 第1章 引论 1.1 引言 1.2 复杂网络研究简史 1.3 基本概念 1.4 本书内容简介 参考文献 第2章 网络拓扑基本模型及其性质 2.1 引言 2.2 规则网络 2.3 随机图 2.4 小世界网络模型 2.5 无标度网络模型 ......一起来看看 《复杂网络理论及其应用》 这本书的介绍吧!

HTML 编码/解码
HTML 编码/解码

HTML 编码/解码

Base64 编码/解码
Base64 编码/解码

Base64 编码/解码

html转js在线工具
html转js在线工具

html转js在线工具