基础:
首先,创建一个文件夹,例如我这里是test-webpack
然后进行 npm 初始化
npm init
创建配置文件 webpack.config.js ,然后安装需要的 webpack 包:
npm i -D webpack webpack-cli
配置入口文件步骤:
在当前文件夹下创建一个 index.js 至于里面,就是你写的代码,我这边随便写当做演示:
index.js
let a = 1;
let b = 2;
let c = 3;
let d = 4;
function test() {
console.log(a + b + c + d);
}
test();
function creataElement() {
let d = document.createElement('div');
d.innerHTML = 'test';
document.body.appendChild(d);
}
creataElement();
然后,修改 webpack.config.js,配置入口文件,并设置为生产环境
module.exports = {
mode: "production",
entry: './index.js',
}
配置输出文件步骤:
修改 webpack.config.js
const path = require('path');
module.exports = {
mode: "production",
entry: './index.js',
output: {
filename: 'bundle.js', // 生成的js 文件
path: path.resolve(__dirname, 'dist'), // 打包生成的文件夹
clean: true,
}
}
修改 package.json 文件,添加 script 下面添加 build 命令
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "webpack"
},
执行
npm run build
就会生成一个 dist 文件夹,下面会有一个我们打包生成的 bundle.js 文件。
对于我们平常的开发,我们一般需要把js代码加载在 html 里面。方便我们调试展示。
添加 html
在 dist 文件夹 添加一个 index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script src="bundle.js"></script>
</body>
</html>
这样就完成了最基础的。
再复杂一点,不能每次都要在dist 文件夹下新建 index.html 。
这时候我们可以这样做,新建 public 文件夹。在里面新建一个 index.html
添加插件:
npm i -D html-webpack-plugin
修改配置文件:
const HtmlWebpackPlugin = require('html-webpack-plugin');
const path = require('path');
module.exports = {
entry: './index.js',
mode: "production",
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist'), // 打包生成的文件夹
},
plugins: [
new HtmlWebpackPlugin({ template: './public/index.html' })
]
}
删除 dist 文件夹,再次执行 npm run build
这样就会新建一个 html 自动会对应到 js 上面。
进阶:
对于我们平时写代码,会频繁的改动js。要及时的展现效果,这里我们就需要 webpack-dev-server ,它为我们提高一个简单的 web server 服务器,并且具有实时重新加载功能。 文档介绍
npm install --save-dev webpack-dev-server
修改配置文件,告知 dev server,从什么位置查找文件,并设置端口为 8080:
const HtmlWebpackPlugin = require('html-webpack-plugin');
const path = require('path');
module.exports = {
entry: './index.js',
mode: "production",
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist'), // 打包生成的文件夹
},
devServer: {
contentBase: path.join(__dirname, 'dist'),
compress: true,
port: 8080,
},
plugins: [
new HtmlWebpackPlugin({ template: './public/index.html' })
]
}
我们添加一个可以直接运行 dev server 的 script:
package.json
"start": "webpack serve --open",
然后执行
npm run start
这个时候打开浏览器, 输入 http://localhost:8080/
就展示页面了。
然后修改 index.js 修改就会更新显示。