一、安装nodejs的环境
二、新建项目
1、在开发工具中新建项目和目录
2、在开发工具的终端执行初始化生成package.json
npm init -y
3、安装yarn
npm install yarn -g
4、安装webpack
yarn add webpack
5、在js目录下和html目录先增加js和html文件
a.js
document.write("hello webpack");
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
</body>
</html>
6、项目根目录下新建webpack配置文件
webpack.config.js
let path = require('path');
let HTMLWebpackPlugin = require('html-webpack-plugin');
let { CleanWebpackPlugin } = require("clean-webpack-plugin");
module.exports = {
mode: 'development', // 模式 模式有两种 production development
entry: './src/js/a.js', // 入口
output: {
filename: "bundle.[hash:8].js", // 打包后的文件名
path: path.resolve(__dirname, 'dist'), // 路径必须是绝对路径
},
plugins: [ // 放着所有的webpack插件
new HTMLWebpackPlugin({
template: "./src/html/index.html",
filename: "index.html",
minify: {
removeAttributeQuotes: true, // 移除引号
collapseWhitespace: true, // 去除换行
},
hash: true
}),
new CleanWebpackPlugin(),//清理dist文件夹
],
};
7、webpack.config.js配置文件中有2个插件要安装
yarn add html-webpack-plugin 用来打包html文件
yarn add clean-webpack-plugin 用来清除dist中的文件
8、打包
执行webpack,生成dist文件夹,webpack版本高的话,还需要安装webpack cli
9、打包后的效果