Webpack5 Vue3 简单打包

项目用到的插件包括:

vue-loader-v16/dist/plugin.js: vueloaderPlugin编译vue需要

html-webpack-plugin:生成入口html文件

webpack-merge:合并配置

terser-webpack-plugin:这个插件使用terser来缩小JavaScript。

clean-webpack-plugin:每次构建前清理dist文件(不是把dist 文件都清空,而是删除打包的那个文件);

项目目录:pages文件夹里放的是多页面的应用,不需要的话,可以不用在意,外层的几个文件就可以。

webpack.config.js:这里面是公共的配置。

/*
  @Author: lize
  @Date: 2021/4/15
  @Description :
  @Parames :
  @Example :
  @Last Modified by: lize
  @Last Modified time: 2021/4/15
 */
const path = require('path');
const fs = require('fs');
const VueLoaderPlugin = require('vue-loader-v16/dist/plugin.js').default;
const HtmlWebpackPlugin = require('html-webpack-plugin');
const { fileExist, readFileSync } = require('./utils');

 const config = {
    mode: 'development',
    entry: path.join(__dirname, '../src/main.ts'), // 入口文件
    output: {
         clean: true, // 清除dist
        filename: 'js/[name].[contenthash].js' // 输出的名字
     },
     optimization: {
         moduleIds: 'deterministic', // 控制公共文件是否编译后hash值发生变化
         runtimeChunk: 'single',
         splitChunks: { // 拆除公共的
             chunks: 'all',
         },
     },
    module: {
        rules: [
            { test: /\.vue$/, loader: 'vue-loader-v16'},
            {
                test: /\.ts$/,
                exclude: /node_modules/,
                use: [
                    {
                        loader: 'ts-loader',
                        options: {
                            appendTsSuffixTo: [/\.vue$/],
                        },
                    },
                ],
            },
            {
                test: /\.js$/,
                exclude: /(node_modules|bower_components)/, // 不处理这两个文件夹里的内容
                loader: 'babel-loader',
            },
            { test: /\.css$/, use: 'css-loader' },
            {
                test: /\.less$/,
                use: ['style-loader','css-loader','less-loader'],
            },
            {
                test: /\.(png|svg|jpg|jpeg|gif)$/i,
                type: 'asset/resource',
            },
            {
                test: /\.(woff|woff2|eot|ttf|otf)$/i,
                type: 'asset/resource',
            },
        ],
    },
    resolve: {
        alias: {
            '@': path.resolve(__dirname, 'src/'),
        },
        extensions: ['.js', '.json', '.jsx', '.css', '.ts'],
        modules: ['node_modules', path.resolve(__dirname, 'app')],
    },
    watchOptions: { // 监听文件变化,重新编译
        aggregateTimeout: 500, // 延迟500毫秒
        ignored: /node_modules/, // 过滤文件
    },
    // 插件
    plugins: [new VueLoaderPlugin()],
}
module.exports = (env, argv) => {
    const entrys = {};
    const htmlPlugins = [];
     if (fileExist(path.join(process.cwd(),'vue.config.js'))) {
         const fileConfig = require(path.join(process.cwd(),'vue.config.js'));
         if (fileConfig.pages) {
             Object.keys(fileConfig.pages).forEach((item) => {
                 entrys[item] = path.join(__dirname, fileConfig.pages[item].entry)
                 htmlPlugins.push(new HtmlWebpackPlugin({
                     title: fileConfig.pages[item].title,
                     filename: fileConfig.pages[item].fileName,
                     template: path.resolve(__dirname, fileConfig.pages[item].template),
                     chunks: ['common', item],
                     hash: true,
                 }));
             })
         }
         console.log(entrys, htmlPlugins);
         config.entry = entrys;
         config.htmlPlugins = htmlPlugins;
     }
    return config;
}

最后抛出去是一个方法,这样就可以接收命令行的其他参数。

webpack.dev.js:这里面是公共的配置。

/*
  @Author: lize
  @Date: 2021/4/15
  @Description :
  @Parames :
  @Example :
  @Last Modified by: lize
  @Last Modified time: 2021/4/15
 */
const path = require('path');
const { merge } = require('webpack-merge');//用于合并两个配置文件的工具
const HtmlWebpackPlugin = require('html-webpack-plugin');
const webpackCommonConfig = require('./webpack.config')();
const config = merge(webpackCommonConfig, {
    mode: 'development',
    devServer: {
        //webpack-server的配置
        host: 'localhost', //服务显示的地址localhsot  127.0.0.1  本机的ip地址都可以
        port: 8090, //服务的端口号
        open: false, //服务启动是否打开浏览器,打开的都是默认的浏览器
        contentBase: './', //服务器加载的目录,会自动找到该目录下的index.html文件进行页面展示
        inline: true, //页面刷新方式
        hot: true, // 开启热更新
        disableHostCheck: true,
        historyApiFallback: true,
        stats: 'minimal',
        compress: true,
    },
    plugins: [
        // new HtmlWebpackPlugin({
        //     // 生成一个html
        //     title: '首页asdasdasdasdasd',
        //     template: path.join(__dirname, '../src/index.html'),
        //     filename: 'index.html',
        //     hash: true,
        // }),
        ...webpackCommonConfig.htmlPlugins,
    ],
    devtool: 'inline-source-map',
});

module.exports =  (env, argv) => {
    delete config.htmlPlugins;
    return config
}

webpack里面不需要多余的配置,所以,最后需要删除自己自定义的属性。

webpack.prod.js:这里面是公共的配置。

/*
  @Author: lize
  @Date: 2021/4/15
  @Description :
  @Parames :
  @Example :
  @Last Modified by: lize
  @Last Modified time: 2021/4/15
 */
const path = require('path');
const TerserPlugin = require("terser-webpack-plugin");
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const webpackCommonConfig = require('./webpack.config')();
const { merge } = require('webpack-merge');//用于合并两个配置文件的工具

const config = merge(webpackCommonConfig, {
    mode: 'production', // 环境变量
    optimization: {
        minimize: true,
        minimizer: [
            new TerserPlugin({
                terserOptions: {
                    format: {
                        comments: false,
                    },
                },
                extractComments: false, // 取出注释
            })
        ]
    },
    plugins: [
        new CleanWebpackPlugin(),
        new HtmlWebpackPlugin({
            // 生成一个html
            title: '首页',
            template: path.join(__dirname, '../src/index.html'),
            filename: 'index.html',
            hash: true,
        })
        // ...webpackCommonConfig.htmlPlugins,
    ]
})

module.exports =  (env, argv) => {
    // delete config.htmlPlugins;
    return config
}

package.json

{
  "name": "webpack5-vue",
  "version": "1.0.0",
  "description": "基于webpack5的一个vue3项目",
  "main": "index.js",
  "scripts": {
    "serve": "webpack serve --config 'build/webpack.dev.js' --mode=development --node-env=111111 --env=werwerwerwre=asdasdasd --env=048503845093845093",
    "build": "webpack build --config 'build/webpack.prod.js'",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "lize",
  "license": "ISC",
  "devDependencies": {
    "@babel/core": "^7.13.15",
    "@babel/plugin-transform-runtime": "^7.13.15",
    "@babel/preset-env": "^7.13.15",
    "@vue/compiler-sfc": "^3.0.11",
    "babel-loader": "^8.2.2",
    "clean-webpack-plugin": "^4.0.0-alpha.0",
    "css-loader": "^5.2.1",
    "html-webpack-plugin": "^5.3.1",
    "less": "^4.1.1",
    "less-loader": "^8.1.0",
    "style-loader": "^2.0.0",
    "terser-webpack-plugin": "^5.1.1",
    "ts-loader": "^8.1.0",
    "typescript": "^4.2.4",
    "vue-loader-v16": "^16.0.0-beta.5.4",
    "webpack": "^5.33.2",
    "webpack-cli": "^4.6.0",
    "webpack-dev-server": "^3.11.2",
    "webpack-merge": "^5.7.3"
  },
  "dependencies": {
    "@babel/runtime": "^7.13.10",
    "axios": "^0.21.1",
    "vue": "^3.0.11",
    "vue-router": "^4.0.6",
    "vuex": "^4.0.0"
  }
}

多页的配置

在根目录下写上vue.config.js

/*
  @Author: lize
  @Date: 2021/4/16
  @Description :
  @Parames :
  @Example :
  @Last Modified by: lize
  @Last Modified time: 2021/4/16
 */
LIZE = 'webpack5-vue';
module.exports = {
    pages: {
        'index-index': {
            entry: '../src/pages/index/index/main.ts',
            template: '../src/pages/index/index/index.html',
            fileName: 'index-index.html',
            title: 'index-index',
        },
        'test-index': {
            entry: '../src/pages/test/index/main.ts',
            template: '../src/pages/test/index/index.html',
            fileName: 'test-index.html',
            title: 'test-index',
        },
    }
};

谢谢大家

github地址:https://github.com/QueerUncle/webpack5-vue3/tree/master

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值