前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >基于create-react-app构建多页面应用框架

基于create-react-app构建多页面应用框架

原创
作者头像
lqmeta
发布2020-07-05 11:43:31
5.1K3
发布2020-07-05 11:43:31
举报
文章被收录于专栏:得一得一

create-react-app 单页面应用框架

代码语言:txt
复制
npx create-react-app multiple-page
cd multiple-page
npm start

运行这些命令会在当前目录中创建一个名为 multiple-page 的目录。在该目录中,它将生成初始项目结构并安装依赖项,目录结构如下所示(tree -I "node_modules"):

代码语言:txt
复制
multiple-page
├── README.md
├── package.json
├── node_modules
├── public
│?? ├── favicon.ico
│?? ├── index.html
│?? ├── logo192.png
│?? ├── logo512.png
│?? ├── manifest.json
│?? └── robots.txt
├── src
│?? ├── App.css
│?? ├── App.js
│?? ├── App.test.js
│?? ├── index.css
│?? ├── index.js
│?? ├── logo.svg
│?? ├── serviceWorker.js
│?? └── setupTests.js
└── yarn.lock

参考资料:

扩展项目 Webpack 的配置

在 multiple-page 的目录下,执行下面指令:

代码语言:txt
复制
npm run eject

构建多页面应用框架

1、修改 src 目录结构

删除 src 目录下的所有文件。删除 public/index.html 文件。

新建 views 文件夹,在 views 文件夹里新建 demo 和 index 文件夹,分别在文件夹中生成同名的 js 文件 和 html 文件,目录结构如下:

代码语言:txt
复制
├── src
│?? ├── components
│?? ├── views
│??     ├── demo
│??     │?? ├── demo.html
│??     │?? └── demo.js
│??     └── index
│??         ├── index.html
│??         └── index.js

js 的代码先简单写了个页面名称:

代码语言:txt
复制
import React from 'react';
import ReactDOM from 'react-dom';

ReactDOM.render(
  <div>
    <h1>index</h1>
  </div>,
  document.getElementById('root')
);

html 的代码如下:

代码语言:txt
复制
<!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" />
    <title>React App</title>
  </head>
  <body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>
  </body>
</html>

2、修改 config/paths.js

由于我们删除了 src/index.js 文件,所以需要更改一下 config/paths.js 文件中的 appIndexJs

代码语言:txt
复制
appHtml: resolveApp('src/views/index/index.html'),
appIndexJs: resolveModule(resolveApp, 'src/views/index/index'),
修改 config/paths.js
修改 config/paths.js

2、修改 webpack 配置

2.1、tools.js

在项目根目录下新建 tools.js 文件(获取 scr/views 文件夹下的页面入口 js),代码如下:

代码语言:txt
复制
const path = require('path');
const glob = require('glob');
const paths = require('./config/paths');
const HtmlWebpackPlugin = require('html-webpack-plugin');

const allSitePath = (isEnvDevelopment) => {
  let entryFiles = glob.sync(paths.appSrc + '/views/*');

  let map = {};
  entryFiles.forEach((item) => {
    let filename = item.substring(item.lastIndexOf('/') + 1);
    let filePath = `${item}/${filename}.js`;

    map[filename] = [
      isEnvDevelopment &&
        require.resolve('react-dev-utils/webpackHotDevClient'),
      filePath
    ].filter(Boolean);
  });

  return map;
}

const htmlPlugin = (isEnvProduction, isEnvDevelopment) => {
  let fileNameLists = Object.keys(
    allSitePath(isEnvDevelopment)
  );

  let arr = [];
  fileNameLists.forEach(item => {
    let filename = item.substring(item.lastIndexOf('/') + 1);

    arr.push(
      // Generates an `index.html` file with the <script> injected.
      new HtmlWebpackPlugin(
        Object.assign(
          {},
          {
            inject: true,
            filename: item + '.html',
            chunks: [item],
            template: path.resolve(paths.appSrc, `views/${filename}/${filename}.html`),
          },
          isEnvProduction
            ? {
                minify: {
                  removeComments: true,
                  collapseWhitespace: true,
                  removeRedundantAttributes: true,
                  useShortDoctype: true,
                  removeEmptyAttributes: true,
                  removeStyleLinkTypeAttributes: true,
                  keepClosingSlash: true,
                  minifyJS: true,
                  minifyCSS: true,
                  minifyURLs: true,
                },
              }
            : ?developer/article/1655789/undefined
        )
      )
    );
  });

  return arr;
}

module.exports = {
  allSitePath,
  htmlPlugin
}

2.2、修复 config/webpack.config.js 配置文件

在 config/webpack.config.js 文件中引入 tools.js 文件:

代码语言:txt
复制
const tools = require('../tools');

1、配置 webpack 入口 entry

代码语言:txt
复制
entry: tools.allSitePath(isEnvDevelopment),
配置 webpack 入口 entry
配置 webpack 入口 entry

2、配置 webpack 的 output

代码语言:txt
复制
filename: isEnvProduction
        ? 'static/js/[name].[contenthash:8].js'
        : isEnvDevelopment && 'static/js/[name].bundle.js',
配置 webpack 的 output
配置 webpack 的 output

3、更改 HtmlWebpackPlugin 配置

代码语言:txt
复制
...tools.htmlPlugin(isEnvProduction, isEnvDevelopment),
更改 HtmlWebpackPlugin 配置
更改 HtmlWebpackPlugin 配置

4、注释掉 ManifestPlugin

代码语言:txt
复制
new ManifestPlugin({s
  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,
    };
  },
}),
注释掉 ManifestPlugin
注释掉 ManifestPlugin

运行项目

代码语言:txt
复制
npm run start

访问 index 页面:

  • http://localhost:3000
  • http://localhost:3000/index.html

访问 demo 页面:

  • http://localhost:3000/demo.html

项目代码:

基于create-react-app构建多页面应用框架

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • create-react-app 单页面应用框架
    • 扩展项目 Webpack 的配置
    • 构建多页面应用框架
      • 1、修改 src 目录结构
        • 2、修改 config/paths.js
        • 2、修改 webpack 配置
          • 2.1、tools.js
            • 2.2、修复 config/webpack.config.js 配置文件
            • 运行项目
            领券
            问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
            http://www.vxiaotou.com