20. webpack优化配置-externals 不打包某些库使用CDN代替

当我们希望使用CDN来引入jquery时,就不需要在打包时将jQuery打包。

  1. 配置webpack配置文件webpack.config.js,添加externals配置

    const path = require('path');
    
    const {
          
          CleanWebpackPlugin} = require('clean-webpack-plugin');
    const HtmlWebpackPlugin = require('html-webpack-plugin')
    
    module.exports = {
          
          
        mode: 'production',
        entry: './src/js/index.js',
        output: {
          
          
            filename: 'js/[name][contenthash:8].js',
            path: path.resolve(__dirname, 'bulid'),
        },
        plugins: [
            new CleanWebpackPlugin(),
            new HtmlWebpackPlugin({
          
          
                template: './src/index.html'
            })
        ],
        externals: {
          
          
        	//不打包jquery文件
            jquery: 'jQuery'
        }
    }
    
  2. 在入口文件index.js中引入jquery

    import $ from 'jquery'
    
    $('#btn').on('click', function (){
          
          
        console.log('click');
    })
    
  3. 在模板文件index.html中使用cdn加载jquery

    <button id="btn">按钮</button>
    <script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
    
  4. 打包

    webpack
    
  5. 在打包信息中可以看到打包后的文件非常小
    在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/kouzuhuai2956/article/details/108094307