webpack4.x简单记录包含(vue手脚架3.x以上vue.config.js)

webpack 执行 需要下载 webpack-cli webpack 还需要配置文件
如果没有就会去当前模块下面的bin文件夹去寻找
如果存在就会使用当前的配置文件

我们也可以 插件模块 npm link 模块
在json里面配置 然后npx 模块 来执行代码

1:比如导入jQuery

const CompressionWebpackPlugin = require("compression-webpack-plugin"); // 开启gzip压缩, 按需引用
const productionGzipExtensions = /\.(js|css|json|txt|html|ico|svg)(\?.*)?$/i; // 开启gzip压缩, 按需写入
const path = require('path')
const webpack = require('webpack')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const CleanWebpackPlugin = require('clear-webpack-plugin')
const CopyWebpackPlugin = require('copy-webpack-plugin')
module.exports = {
    
    
	entry:{
    
     //多入口
	},
	optimization:{
    
    
	splitChunks:{
    
    //分割代码模块
	cacheGroups:{
    
    //缓存组
		common:{
    
     //公共模块
		chunks: 'initial',
		minSize: 0,
		minChunks: 2 //
		},
		vendor:{
    
    
			priority:1, // 引用
			test: /node_modules/ ,//抽离
			chunks: 'initial',
			minSize: 0,
			minChunks: 2 //
		}
	}
	}
}, // 最好是4.x最高的版本
	output: {
    
    
	template:'',//指定html文件做输出打包
	filename:'[name].js',//入口js文件打包输出名字
	path:''//打包文件位置
	},
	module:{
    
    
	rules: [
		{
    
    test:/\.js$/,use:'babel-loader',exclude:/node_module/},
		{
    
    test:require.resolve('jquery'),
		use:'expose-loader?$'
	}
	]
	},
	plugins:[
		new HtmlWebpackPlugin({
    
    
	template:'',//指定本地HTML输出
	filename:'',//运行服务器html文件名字,
	minify:{
    
    
	removeAttributeQuotes: true,//移除双引号
	collapseWhitespace: true,//缩进空格
	},
	chunk:[],//多文件加载 多个入口使用多次插件运行
	hash: true,//打包文件出现hahs值
	}),
	new webpack.DefinePlugin({
    
    
		DEV:'true', //不包含引号
		dev:JSON.stringify('123'),//包含引号
	}),//内置webpack插件
	new CompressionWebpackPlugin({
    
     // 压缩除图片 视频 音频之外的 html css js txt 等等
               filename: "[path].gz[query]",
               algorithm: "gzip",
               test: productionGzipExtensions,///\.(js|css|json|txt|html|ico|svg)(\?.*)?$/i;
               threshold: 10240,
               minRatio: 0.8
    }),
	new CleanWebpackPlugin('./dist'),//打包先删除
	new CopyWebpackPlugin([{
    
    form:'doc',to:'./'}]),
	//form 文件名字 to到哪里去 注意文件层级
	new webpack.BannerPlugin('打包开头个性签名'),
	new webpack.NameModulesPlugin(),
	// 打印更新模块路径
	new webpack.HotModuleReplacementPlugin()
	//热更新
	],
	externals:{
    
     //避免打包没有必要的模块
	jquery:'jquery'
	},
	resolve:{
    
    
		alias:{
    
    },//别名
		extensions:['.js','.css','.json'],
		//同名模块导入省略后缀优先匹配顺序
		modules:[ path.resolve('node_modules')]
		//作用与第三方模块
	},
	devServer:{
    
    
		proxy:{
    
    
	
		}
	},
	watch: true,// 监听
	watchOptions: {
    
    
		poll: '',// 每秒监听多少次
		aggregateTimeout: '', // 防抖间隔
		ignore:/node_modules/	 // 不需要监控
	},
	devtool: '' //source-map 增加映射文件 正式版打包调试 代码 产生单独文件 有行有列
	// eval-source-map 不产生文件 有行与列
	//cheap-module-source-map 有行没有列 单独映射
}

如上是webpack配置文件
使用webpack-dev-middleware插件
可以把配置运行与服务器
let midd = require(’’)
app.use(midd(webpack.config.js))
注册express配置 执行开始即刻打包运行

webpack自身优化
import导入在生产环境下面 会自动除掉没有用的代码 根据引用的次数 来判断依赖 标记文件 来执行打包删除
使用require导入的模块 不会自动除掉 会把内容打包在对象的default属性下面
webpack会执行处理输出最终结果
存在scope hosting 作用域提升


css预编译
使用style-loader 向节点添加style 或者link
然后使用less sass loader 处理返回css字符串
最后使用css-loader形成语法树
遍历产生样式
根据是否是首页还是其他页面
来使用style还是link
preload首页立即加载执行 prefetch加载 触发条件执行

2021-1-25更新 vue-cli4.x版本配置

const appData = {
    
    
  data1:12,
  data2:121,
  data3:1212
}
const data1 = appData.data1;
const data2 = appData.data2;
const data3 = appData.data3;

const path =  require('path');

const CompressionWebpackPlugin = require("compression-webpack-plugin"); // 开启gzip压缩, 按需引用
const productionGzipExtensions = /\.(js|css|json|txt|html|ico|svg)(\?.*)?$/i; // 开启gzip压缩, 按需写入
const BundleAnalyzerPlugin = require("webpack-bundle-analyzer").BundleAnalyzerPlugin; // 打包分析

const IS_PROD = ['production', 'prod'].includes(process.env.NODE_ENV);
const resolve = (dir) => path.join(__dirname, dir);
module.exports = {
    
    
    publicPath: process.env.NODE_ENV === 'production' ? './' : '/',  // 公共路径
    indexPath: 'index.html' , // 相对于打包路径index.html的路径
    outputDir: process.env.outputDir || 'dist', // 'dist', 生产环境构建文件的目录
    assetsDir: 'static', // 相对于outputDir的静态资源(js、css、img、fonts)目录
    lintOnSave: false, // 是否在开发环境下通过 eslint-loader 在每次保存时 lint 代码
    runtimeCompiler: true, // 是否使用包含运行时编译器的 Vue 构建版本
    productionSourceMap: !IS_PROD, // 生产环境的 source map
    pwa: {
    
    }, // 向 PWA 插件传递选项。
    chainWebpack: config => {
    
    
        config.resolve.symlinks(true); // 修复热更新失效
        // 如果使用多页面打包,使用vue inspect --plugins查看html是否在结果数组中
        config.plugin("html").tap(args => {
    
    
            // 修复 Lazy loading routes Error
            args[0].chunksSortMode = "none";
            return args;
        });
        config.resolve.alias // 添加别名
            .set('@', resolve('src'))
            .set('@assets', resolve('src/assets'))
            .set('@components', resolve('src/components'))
            .set('@views', resolve('src/views'))
            .set('@store', resolve('src/store'));
        // 压缩图片
        // 需要 npm i -D image-webpack-loader
        config.module
            .rule("images")
            .use("image-webpack-loader")
            .loader("image-webpack-loader")
            .options({
    
    
                mozjpeg: {
    
     progressive: true, quality: 65 },
                optipng: {
    
     enabled: false },
                pngquant: {
    
     quality: [0.65, 0.9], speed: 4 },
                gifsicle: {
    
     interlaced: false },
                webp: {
    
     quality: 75 }
            });
        // 打包分析
        // 打包之后自动生成一个名叫report.html文件(可忽视)
        if (IS_PROD) {
    
    
            config.plugin("webpack-report").use(BundleAnalyzerPlugin, [
                {
    
    
                    analyzerMode: "static"
                }
            ]);
        }
    },
    configureWebpack: config => {
    
    
        // 开启 gzip 压缩
        // 需要 npm i -D compression-webpack-plugin
        const plugins = [];
        if (IS_PROD) {
    
    
            plugins.push(
                new CompressionWebpackPlugin({
    
    
                    filename: "[path].gz[query]",
                    algorithm: "gzip",
                    test: productionGzipExtensions,
                    threshold: 10240,
                    minRatio: 0.8
                })
            );
        }
        config.plugins = [...config.plugins, ...plugins];
    },
    // css: { // css 可以不要  如果导入组件库了
    //     extract: IS_PROD,
    //     requireModuleExtension: false,// 去掉文件名中的 .module
    //     loaderOptions: {
    
    
    //             // 给 less-loader 传递 Less.js 相关选项
    //             less: {
    
    
    //                 // `globalVars` 定义全局对象,可加入全局变量
    //                 globalVars: {
    
    
    //                     primary: '#333'
    //                 }
    //             }
    //     }
    // },
    devServer: {
    
    
      before(app) {
    
     // 用于mock数据 切记如果设置了路由重定向 或者 路径冲突 没有用
      //请发送请求 axios 比如axios.get('/api/data1')
              app.get('/api/data1', function (req, res) {
    
    
                res.json({
    
    
                  errno: 0,
                  data: data1
                });
              });
              app.get('/api/data2', function (req, res) {
    
    
                res.json({
    
    
                  errno: 0,
                  data: data2
                });
              });
              app.get('/api/data3', function (req, res) {
    
    
                res.json({
    
    
                  errno: 0,
                  data: data3
                });
              });
            },
            overlay: {
    
     // 让浏览器 overlay 同时显示警告和错误
              warnings: true,
              errors: true
            },
            host: "localhost",//127.0.0.1
            port: 8080, // 端口号
            https: false, // https:{type:Boolean}
            open: false, //配置自动启动浏览器
            hotOnly: true, // 热更新
            // proxy: 'http://localhost:8080'   // 配置跨域处理,只有一个代理
            proxy: {
    
     //配置多个跨域
                "/api": {
    
    
                    target: "http://172.11.11.11:7071",
                    changeOrigin: true,
                    // ws: true,//websocket支持
                    secure: false,
                    pathRewrite: {
    
    
                        "^/api": "/"
                    }
                },
                "/api2": {
    
    
                    target: "http://172.12.12.12:2018",
                    changeOrigin: true,
                    //ws: true,//websocket支持
                    secure: false,
                    pathRewrite: {
    
    
                        "^/api2": "/"
                    }
                },
            }
        }
}

猜你喜欢

转载自blog.csdn.net/qq_43505774/article/details/111772723