Webpack 第三方库与业务代码打包分离

项目目录结构:

1.package.json配置:

{
 // ...  
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "webpack-dll": "webpack --config ./webpack.dll.conf.js",
    "build": "webpack --config ./webpack_config/webpack.prod.conf.js",
    "dev": "webpack-dev-server --open --config ./webpack_config/webpack.dev.conf.js"
  },
  "dependencies": {
    "axios": "^0.18.0",
    "lodash": "^4.17.11",
    "vant": "^1.6.12",
    "vue": "^2.6.10",
    "vue-axios": "^2.1.4",
    "vue-router": "^3.0.2",
    "vuex": "^3.1.0"
  },
  "devDependencies": {
    "babel-core": "^6.26.3",
    "babel-loader": "^7.0.0",
    "babel-plugin-transform-runtime": "^6.23.0",
    "babel-preset-es2015": "^6.24.1",
    "clean-webpack-plugin": "^2.0.1",
    "copy-webpack-plugin": "^5.0.2",
    "css-loader": "^2.1.1",
    "del": "^4.1.0",
    "file-loader": "^3.0.1",
    "gulp": "^3.9.1",
    "gulp-sftp": "^0.1.5",
    "html-webpack-include-assets-plugin": "^1.0.7",
    "html-webpack-plugin": "^3.2.0",
    "mockjs": "^1.0.1-beta3",
    "style-loader": "^0.23.1",
    "uglifyjs-webpack-plugin": "^2.1.2",
    "url-loader": "^1.1.2",
    "vue-loader": "^15.7.0",
    "vue-template-compiler": "^2.6.10",
    "webpack": "^4.29.6",
    "webpack-cli": "^3.3.0",
    "webpack-dev-server": "^3.2.1",
    "webpack-merge": "^4.2.1"
  }
// ...
}

2. webpack.dll.conf.js配置:

//webpack.dll.conf.js
const path = require('path')
const webpack = require('webpack')
const CleanWebpackPlugin = require("clean-webpack-plugin")

const static = path.resolve(__dirname, './dll/assets')

module.exports = {
    mode: 'development',
    context: __dirname,
    entry: {
        'core': ['vue', 'vue-router', 'vuex'],
        'assets': ['axios', 'lodash']
    },
    output: {
        path: path.resolve(static, 'lib'),
        filename: '[name]-[chunkhash:7].dll.js',
        library: 'lib_[name]'
    },
    resolve: {
        modules: [path.resolve(__dirname, 'node_modules')],
        extensions: ['.js', '.json'],
        alias: {
            'vue$': 'vue/dist/vue.esm.js'
        }
    },
    plugins: [
        new CleanWebpackPlugin({
            cleanOnceBeforeBuildPatterns: ['**/*', '!static-files*'],
            verbose: true,
            dry: false
        }),
        new webpack.DllPlugin({
            path: path.resolve(__dirname, './dll/manifest/[name].manifest.json'),
            name: 'lib_[name]'
        }),
        /*new webpack.HashedModuleIdsPlugin(),
        new webpack.NamedChunksPlugin()*/
    ]
}

3.webpack.base.conf.js 配置:

const path = require('path');
const VueLoaderPlugin = require('vue-loader/lib/plugin');


module.exports = {
    entry: {
        app: './src/main.js'
    },
    output: {
        path: path.resolve(__dirname, '../dist'),
        filename: "bundle.js"
    },
    plugins: [
        new VueLoaderPlugin()
    ],
    module: {
        rules: [
            {
                test: /\.css$/,
                use: ['style-loader', 'css-loader']
            },
            {
                test: /\.js$/,
                loader: 'babel-loader',
                exclude: /node_modules/,

            },
            {
                test: /\.vue$/,
                use: 'vue-loader'
            },
            {
                test:/\.(png|jpg|gif|svg)$/,
                loader: 'url-loader',
                query: {
                    limit: 10000,
                    name: 'assets/images/[name]-[hash:5].[ext]'
                }
            }
        ]
    },
    resolve: {
        alias: {
            'vue$': 'vue/dist/vue.esm.js'
        }
    }
};

4. webpack.dev.conf.js 配置:

const merge = require('webpack-merge');
const base = require('./webpack.base.conf.js');

module.exports = merge(base, {
    mode: 'development',
    devtool: 'inline-source-map',
    devServer: {
        historyApiFallback: true,
        contentBase: './dist'
    }
});

4.webpack.prod.conf.js 配置:

const path = require('path');
const merge = require('webpack-merge');
const webpack = require('webpack');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const CleanWebpackPlugin = require("clean-webpack-plugin");
const HtmlWebpackPlugin = require('html-webpack-plugin');
const HTMLWebpackIncludeAssetsPlugin = require('html-webpack-include-assets-plugin');
const UglifyJSPlugin = require('uglifyjs-webpack-plugin');
const WebpackDllConfig = require('../webpack.dll.conf');
const base = require('./webpack.base.conf.js');

// 获取dll文件的manifest
function getDllManifest () {
    let plugins = [];
    Object.keys(WebpackDllConfig.entry).forEach((name) => {
        plugins.push(
            new webpack.DllReferencePlugin({
                context: __dirname,
                manifest: path.resolve(__dirname, '../dll/manifest/[name].manifest.json').replace(/\[name\]/gi, name)
            })
        )
    });
    return plugins
}

module.exports = merge(base, {
    mode: 'production',
    devtool: 'source-map',
    plugins: [
        new UglifyJSPlugin({
            sourceMap: true
        }),
        new webpack.DefinePlugin({
            'process.env.NODE_ENV': JSON.stringify('production')
        }),
        new CleanWebpackPlugin({
            cleanOnceBeforeBuildPatterns: ['**/*', '!static-files*'],
            verbose: true,
            dry: false
        }),
        ...getDllManifest(),
        new HtmlWebpackPlugin({
            filename: 'index.html',
            template: path.resolve(__dirname, '../index.html'),
            inject: true,
            minify: {
                removeComments: true,
                collapseWhitespace: true,
                removeAttributeQuotes: true
            },
            chunksSortMode: 'dependency'
        }),
        // dll文件需要插件将其引入到html文件中,以方便后续使用
        new HTMLWebpackIncludeAssetsPlugin({
            append: false,
            publicPath: '',
            assets: [{
                path: 'assets',
                glob: '**/*.js',
                globPath: path.resolve(__dirname, '../dll/assets'),
            }],
        }),
        // 将dll文件拷贝到你的dist目录下
        new CopyWebpackPlugin([
            {
                // 这里是dll文件当前所在的文件目录
                from: path.resolve(__dirname, '../dll/assets'),
                // 这里是生产环境的资源地址
                to: path.resolve(__dirname, '../dist/assets'),
                // 过滤static中的部分文件
                ignore: ['.*', 'manifest/*']
            }
        ])
    ]
});

执行 npm run webpack-dll会生成对应的 dll 打包文件,再执行 npm run build 就可以啦!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值