8.webpack 资源内联
- 资源内联:将js,css的代码内联到Html代码中去,它可以减少Http网络请求,有利于页面初始化以及css内联可以避免页面闪动等意义
- Html内联和js内联
- 安装 npm i raw-loader@0.5.1 -D 目前0.5版本的比较稳定
- 在页面中引入
- Css内联
- 多页面应用:每一次跳转,后台都会返回一个新HTML文件
- 多页面打包思路:每一个页面对应一个entry,一个html-webpack-plugin。每次增加和修改页面都需要修改webpack配置
- 通用方案:使用glob.sync动态获取entry和设置html-webpack-plugin
- 安装 npm i glob -D
-
'use strict'; 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]; // '/Users/cpselvis/my-project/src/index/index.js' 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:8].js' }, mode: 'production', module: { rules: [ { test: /.js$/, use: [ 'babel-loader', // 'eslint-loader' ] }, { test: /.css$/, use: [ MiniCssExtractPlugin.loader, 'css-loader' ] }, { test: /.less$/, use: [ MiniCssExtractPlugin.loader, 'css-loader', 'less-loader', { loader: 'postcss-loader', options: { plugins: () => [ require('autoprefixer')({ browsers: ['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), };
浪波激泥