准备工作

  • vscode
  • node V16.13.1
  • npm V8.17.0

项目初始化

首先在想要的位置新建一个空的文件夹,这里取名为 webpack,然后进入该文件夹执行命令

1
2
// 初始化项目
npm init -y

我们会得到一个 package.json

此时项目结构如下

1
2
webpack
|- package.json;

接下来安装 webpack

1
2
// 初始化项目
npm install webpack webpack-cli --save-dev

此时项目结构如下

1
2
3
4
webpack
|- /node_modules;
|- package-lock.json
|- package.json;

我们还需要调整 package.json 文件,以便确保我们安装包是 private(私有的),并且移除 main 入口。这可以防止意外发布你的代码。
使用在 package.json 文件中

1
2
3
4
5
// 删除
"main": "index.js",

// 增加
"private": true,

创建一个 src 文件夹,里面存放 html,js

1
2
3
4
5
6
7
8
webpack
|- /node_modules;
|- /src
|- index.html
|- index.js
|- package-lock.json
|- package.json;

1
2
3
4
5
6
7
8
9
10
11
12
13
<!-- 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>
<p>hello webpack</p>
</body>
</html>
1
2
// index.js
console.log('hello webpack');

准备配置文件

在跟目录下创建 webpack.config.js
此时项目结构为

1
2
3
4
5
6
7
8
webpack
|- /node_modules;
|- /src
|- index.html
|- index.js
|- package-lock.json
|- package.json;
|- webpack.config.js

webpack.config.js的内容为

1
2
3
4
5
6
7
8
9
const path = require('path');

module.exports = {
entry: './src/index.js',
output: {
filename: 'main.js',
path: path.resolve(__dirname, 'dist'),
},
};

调整 package.json,在 script 中

1
2
// 增加
"build": "webpack"

img

此时我们可以运行npm run build
可以看到在根目录下增加了一个 dist 文件夹
此时的项目结构

1
2
3
4
5
6
7
8
9
10
webpack
|- /dist
|-main.js
|- /node_modules;
|- /src
|- index.html
|- index.js
|- package-lock.json
|- package.json;
|- webpack.config.js