1. 程式人生 > 實用技巧 >8.webpack 資源內聯

8.webpack 資源內聯

  1. 資源內聯:將js,css的程式碼內聯到Html程式碼中去,它可以減少Http網路請求,有利於頁面初始化以及css內聯可以避免頁面閃動等意義
    1. Html內聯和js內聯
      1. 安裝npm i [email protected] -D 目前0.5版本的比較穩定
      2. 在頁面中引入
    2. Css內聯
  2. 多頁面應用:每一次跳轉,後臺都會返回一個新HTML檔案
    1. 多頁面打包思路:每一個頁面對應一個entry,一個html-webpack-plugin。每次增加和修改頁面都需要修改webpack配置
    2. 通用方案:使用glob.sync動態獲取entry和設定html-webpack-plugin
      1. 安裝npm i glob -D
      2. '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), };