我们的程序是单页面应用,但我们需要把登陆页抽离成,单独的一个 html 文件。所以我专门抽离出了 login。(登陆时不需要加载过多文件)
技术要点分析
要点还是webpack进行文件打包时配置多个入口,打包出多个文件。以下是 webpack 官网对多人口的代码。
entry: {
app: './src/app.js',
search: './src/search.js'
},
output: {
filename: '[name].js',
path: __dirname + '/dist'
}
之后的问题就是,将打包后的文件引入 html 文件。这就需要修改 脚手架中中的 HtmlWebpackPlugin 配置了。HtmlWebpackPlugin 又一个chunks参数可以,限定引入的文件。
plugins: [
new HtmlWebpackPlugin({
chunks: ['app']
})
]
配置修改
paths.js 新增文件路径
paths.js 文件中 module.exports 内新增两个基础配置
loginHtml: resolveApp('public/login.html'),
loginIndexJs: resolveModule(resolveApp, 'src/login')
webpack.config.js 中文件修改
打包入口 entry 中新增 login 入口
login: [
isEnvDevelopment &&
require.resolve('react-dev-utils/webpackHotDevClient'),
paths.loginIndexJs,
].filter(Boolean)
打包输出 output 中改为
filename: isEnvProduction
? 'static/js/[name].[contenthash:8].js'
: isEnvDevelopment && 'static/js/[name]/[name].bundle.js',
···
chunkFilename: isEnvProduction
? 'static/js/[name].[contenthash:8].chunk.js'
: isEnvDevelopment && 'static/js/[name]/[name].chunk.js',
新增 H
new HtmlWebpackPlugin(
Object.assign(
{},
{
inject: true,
chunks: ['login'],
template: paths.loginHtml,
filename: 'login.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 这是为了生成 manifest.json 文件的配置,这里不需要。
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,
};
},
}),
(Manifest.json文件是5+移动App的配置文件,用于指定应用的显示名称、图标、应用入口文件地址及需要使用的设备权限等信息,类似于android里面的manifest.xlm配置文件)
添加 src 中文件 longin.js
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import * as serviceWorker from './serviceWorker';
import Login from './Login/Login'
ReactDOM.render(
<Login />
, document.getElementById('root'));
serviceWorker.unregister();