我在经过读10篇webpack相关超火的文章,并深入webpack源码,最后决定写一个webpack系列文章。
给我6分钟教会你上手。
webpack——一个成熟稳定,使用量最多的前端打包工具。这么厉害的工具,还不赶紧学?
先学一下使用吧,不过你要先学js和html和css哈。
一般webpack的配置文件是这样的:
webpack.dev.js
webpack.prod.js
webpack.xxx.js
我以为,最简单的配置是这样的。其中entry是你要打包文件的入口,至于index.js引用的文件,webpack会帮你处理好。
module.exports = {
entry: 'index.js',
};
结果实验后,发现你可以这样(啥也不写)
// 前提是当前目录下有src目录,而且src目录下面有index.js
那么一个至少在浏览器跑得起来的,用webpack打包的项目张什么样子呢?
demo001
├─index.html
├─package.json
└─src
└─index.js
其中package.json是为了安装依赖,方便输入srcipt命令,如果你不想管理依赖甚至可以不要。
{
"name": "demo001",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"build": "webpack",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"webpack": "^5.74.0"
},
"devDependencies": {
"webpack-cli": "^4.10.0"
}
}
index.html引入打包好的文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script src="./dist/main.js"></script>
</body>
</html>
index.js里面。为了演示,我不得不写了一个console
console.log('hello world')
最后,你需要安装依赖npm i
,还需要npm run build
.
你学会了吗?
紧接着我写了一个 test.js文件
export function test(params) {
console.log('test被调用了')
}
让它被index.js引用
import { test } from './test'
console.log('hello world')
test()
使用npm run build
,发现生成文件dist/main.js
变成了
(()=>{"use strict";console.log("hello world"),console.log("test被调用了")})();
嗯!!!∑(゚Д゚ノ)ノ
别慌,这是立即执行函数,学过作用域你应该知道,在实际开发中,各种函数和变量的作用域非常复杂,为了避免变量污染(特别是各种第三方库的质量很难把控)。它可以用来隔离变量作用域,常用于各种第三方库。
配置webpack.config.js 文件
module.exports = {
module: {
rules: [{ test: /\.css$/, use: ['style-loader', 'css-loader'] }],
},
}
随便写一下index.css,来个猛男粉
body {
background: pink;
}
让它被index.js引用
import { test } from './test'
import './index.css'
console.log('hello world')
test()
然后执行命令npm i -D style-loader css-loader
,等安装完成后,再等执行完npm run build
,在浏览器中打开index.html,你就可以看到一个正常的项目了
等等,我发现此时webpack打包的内容又双变了。
其实很简单,它需要用一些代码,来用js更新dom的样式。这些代码类似于给你的网站一键动态换皮肤中所说的,大家有兴趣可以看看。
本系列文章实例地址:https://github.com/PangYiMing/webpackDemo
参考文章: webpack 官网: https://webpack.docschina.org/
有一起学的伙伴,可以提issue和pr,欢迎一起。