Webpack5 高级篇

1 dev开发环境配置

1.1 config配置

mode: 'development',

devtool: 'cheap-module-source-map',

devServer: 

        hot:true //热加载

const HtmlWebpackPlugin = require('html-webpack-plugin');
const path = require('path');

module.exports = {
	entry: './src/index.js',
	// webpack会针对不通环境特殊处理
	mode: 'development',
	// 会单独生成map文件,减少bundle体积
	devtool: 'cheap-module-source-map',
	output: {
		filename: 'bundle.js',
		clean: true,
	},

	devServer: {
		// 页面直接输localhost:3000 会找dist下index.html
		static: path.resolve(__dirname, 'dist'),
		// 压缩 生产应当为true
		compress: false,
		server: 'https',
		// 配置地址,可供外部访问
		host: '0.0.0.0',
		port: 3000,
		// 加代理,路径匹配时,将请求转发
		proxy: [
			{
				context: ['/api'],
				target: 'http://localhost:9000',
			},
		],
		// 添加所有响应头添加参数
		headers: [
			{
				key: 'X-Custom',
				value: 'foo',
			},
			{
				key: 'Y-Custom',
				value: 'bar',
			},
		],
		// 路由模式配置history时,避免刷新404
		historyApiFallback: true,
		// false时,改变css配置,会整个页面刷新,之前添加的元素也丢失了
		// true时 热插拔,只样式改变
		hot: true,
	},

	plugins: [
		new HtmlWebpackPlugin({
			template: 'index.html',
			filename: 'app.html',
		}),
	],

	module: {
		rules: [
			{
				test: /\.js$/,
				exclude: /node_modules/,
				use: {
					loader: 'babel-loader',
					options: {
						presets: ['@babel/preset-env'],
					},
				},
			},
			{
				test: /\.css$/,
				use: ['style-loader', 'css-loader'],
			},
		],
	},
};

1.2 eslint 代码格式检查

安装及初始化

#安装
yarn add eslint -D

#初始化配置
npx eslint --init

.eslintrc.json 文件配置

{
    "env": {
        "browser": true,
        "es2021": true
    },
    "extends": [
        "airbnb-base"
    ],
    "parserOptions": {
        "ecmaVersion": 13,
        "sourceType": "module"
    },
    "rules": {
        // 换行
        "linebreak-style": [
            0,
            "error",
            "window"
        ],
        // 引号,允许es6模板语法
        "quotes": ["error", "single", { "allowTemplateLiterals": true }],
        // 缩进
        "indent": ["error", "tab"],
        // 不检测console
        "no-console":"off",
        // tab
        "no-tabs": ["error", { "allowIndentationTabs": true }]

    },
    "globals": {}
}

校验文件

npx eslint ./src 

npx eslint ./src --fix 检测+修复

1.2.1 eslint 插件

eslint 编写过程中带提示,更友好。

1.2.2 git-hook 提交前校验

使用第三方库 husky

npm install husky -D

配置提交前的命令

git提交代码时会自动校验

2 css优化扩展

2.1 postcss-loader

插件:

  1. autoprefixer:自动加前缀
  2. postcss-nested:允许嵌套写法

2.2 css-loader 

modules功能:自动生成类名,避免命名重复

2.3 配置示例

webpack.config.js

module.exports = {
	entry: './src/index.js',
	// webpack会针对不通环境特殊处理
	mode: 'development',
	module: {
		rules: [
			{
				test: /\.css$/,
				use: ['style-loader',
					{
						loader: 'css-loader',
						options: {
							// 开启css模块,生成类名,避免命名冲突
							modules: true,
						}
					},
					'postcss-loader'],
			},
		],
	},
};

新建postcss.config.js ,配置插件

module.exports = {
	plugins: [
		// 自动前缀,以适配不同版本浏览器
		require('autoprefixer'),
		// 允许css嵌套写法
		require('postcss-nested'),
	]
}

css文件:嵌套写法

body{
    background-color: red;
    display: flex;
    .box{
        width: 100px;
        height: 100px;
        background: yellow;
    }
}

引入css并使用样式

import * as style from './style.css';

const div = document.createElement('div');
div.textContent = "hello postcss";
//此处使用对象写法,非'box'
div.classList.add(style.box);
document.body.appendChild(div);

效果:

css模块

3 ts配置

如果不配置ts-loader,webpack无法解析ts文件

安装:npm i typescript ts-loader -D

config配置:

	module: {
		rules: [
			{
				test:/\.(ts|tsx)$/,
				use:'ts-loader',
				exclude:/node_modules/,
			}
		],
	},
    //配置解析后缀的优先级
	resolve:{
		extensions:['.tsx','.ts','.js']
	}

4 Tree shaking

摇树,摇掉黄了的叶子,根据import,export 将导出但是没用的对象删除掉。(lodash只引用不用,不会删除)

测试文件

export const add = (x, y) => {
    return x + y;
}

export const minus = (x, y) => {
    return x - y;
}

未启用tree shaking结果

配置webconfig

module.exports = {
	entry: './src/index.js',
	//启用export
	optimization: {
		usedExports: true,
	}
};

启用结果:

5 sideEffects

是否有副作用

true:都有副作用,都不删

false:都没有副作用,都可删除

数组:定义哪些有副作用

package.json中配置

{
  "name": "webpack_test",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "sideEffects": ["*.css","*.global.js"]
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值