说明
玩转webpack
课程学习笔记。
多页面打包(MPA)概念
每⼀次⻚⾯跳转的时候,后台服务器都会给返回⼀个新的 html
⽂档,
这种类型的⽹站也就是多⻚⽹站,也叫做多⻚应⽤
。
多页面打包基本思路
1、每个⻚⾯对应⼀个 entry
,⼀个 html-webpack-plugin
2、缺点:每次新增或删除⻚⾯需要改 webpack
配置
module.exports = { entry: { index: './src/index.js', search: './src/search.js' } };
多页面打包通用方案
1、动态获取 entry
和设置 html-webpack-plugin
数量
2、利用 glob.sync
安装依赖
npm i glob -D
entry: glob.sync(path.join(__dirname, './src/*/index.js'))
module.exports = { entry : { index: './src/index/index.js', search: './src/search/index.js' } }
例子
1、先将对应的文件放到单独的文件夹里面,并修改里面的文件资源的引用
2、修改webpack的配置
const glob = require('glob'); const path = require('path'); const webpack = require('webpack'); const MiniCssExtractPlugin = require('mini-css-extract-plugin'); const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const { CleanWebpackPlugin } = require('clean-webpack-plugin'); const setMPA = () => { const entry = {}; const htmlWebpackPlugins = []; const entryFiles = glob.sync(path.join(__dirname, './src/*/index.js')); Object.keys(entryFiles) .map((index) => { const entryFile = entryFiles[index]; const match = entryFile.match(/src\/(.*)\/index\.js/); const pageName = match && match[1]; entry[pageName] = entryFile; htmlWebpackPlugins.push( new HtmlWebpackPlugin({ inlineSource: '.css$', template: path.join(__dirname, `src/${pageName}/index.html`), filename: `${pageName}.html`, chunks: ['vendors', pageName], inject: true, minify: { html5: true, collapseWhitespace: true, preserveLineBreaks: false, minifyCSS: true, minifyJS: true, removeComments: false } }) ); }); return { entry, htmlWebpackPlugins } } const { entry, htmlWebpackPlugins } = setMPA(); module.exports = { entry: entry, output: { path: path.join(__dirname, 'dist'), filename: '[name]_[chunkhash].js' }, mode: 'production', module: { rules: [ { test: /.js$/, use: 'babel-loader' }, { test: /.css$/, use: [ MiniCssExtractPlugin.loader, 'css-loader' ] }, { test: /.less$/, use: [ MiniCssExtractPlugin.loader, 'css-loader', 'less-loader', { loader: 'postcss-loader', options: { plugins: () => [ require('autoprefixer')({ overrideBrowserslist: ['last 2 version', '>1%', 'ios 7'] }) ] } }, { loader: 'px2rem-loader', options: { remUnit: 75, remPrecision: 8 } } ] }, { test: /.(png|jpg|gif|jpeg)$/, use: [ { loader: 'file-loader', options: { name: '[name]_[hash:8].[ext]' } } ] }, { test: /.(woff|woff2|eot|ttf|otf)$/, use: [ { loader: 'file-loader', options: { name: '[name]_[hash:8].[ext]' } } ] }, ] }, plugins: [ new MiniCssExtractPlugin({ filename: '[name]_[contenthash:8].css' }), new OptimizeCSSAssetsPlugin({ assetNameRegExp: /\.css$/g, cssProcessor: require('cssnano') }), new CleanWebpackPlugin() ].concat(htmlWebpackPlugins) };
3、如图