[TOC]
## 1.配置前的準備//將倉庫改為淘寶
* 使用webpack必須安裝node.js環境;
### npm安裝太慢可以安裝cnpm,走淘寶的倉庫
```
npm install -g cnpm --registry=https://registry.npm.taobao.org
```
## 2.webpack環境配置
```
npm init -y
npm i webpack webpack-cli -g
//走完這倆步如圖 出現`webpack.json`文件
```

```
npm i webpack webpack-cli --save-dev
//運行完成出現如下文件
```

* 建一個 `src / index.js `文件和 `webpack.config.js `文件
* 文件內容
```
//index.js
var a = 10;
console.log(10);
```
[webpack官網](https://www.webpackjs.com/)
> webpack.config.js 直接復制官網
```
//webpack.config.js
const path = require('path');
module.exports = {
entry: './src/index.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.js'
}
};
```
* 控制臺輸入`webpack` 出現如下圖的文件及目錄 `dist/bundle.js`

## 3.html-webpack-plugin
### 3.1安裝
```
npm i html-webpack-plugin --save-dev
```
### 3.2引入
在webpack.config.js文件中
```
//webpack.config.js
const htmlWebpackPlugin = require('html-webpack-plugin')
```
### 3.3 使用
```
//webpack.config.js
//在plugins中使用++
plugins:[
new htmlWebpackPlugin({
title:"打包文件",
inject:"head"
})
]
};
```
* webpack 出現 `dist/index.html`


## 4. style-loader,css-loader
### 4.1 安裝
```
npm i style-loader css-loader --save-dev
```
### 4.2 在入口的js中引入css

### 4.3 使用
```
module: {
rules: [
{
test: /\.css$/,
use: [
{ loader: "style-loader" },
{ loader: "css-loader" }
]
}
]
},
```

## 5.clean-webpack-plugin
## 5.1安裝
```
npm i clean-webpack-plugin --save-dev
```
### 5.2引入
```
//webpack.config.js
const cleanWebpackPlugin = require('clean-webpack-plugin');
```
### 5.3 為了不重名 html 需要改成隨機的
#### 1.刪掉dist
#### 2.建一個 index.html

#### 3. 修改webpack.config.js
```
//webpack.config.js
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin'); // 通過 npm 安裝
const CleanWebpackPlugin = require('clean-webpack-plugin');
module.exports = {
entry: './src/index.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: '[hash].bundle.js'
},
plugins: [
new CleanWebpackPlugin(['dist']),
new HtmlWebpackPlugin({
title:"打包文件",
inject:"head",
template:"index.html",
filename:'[hash]-index.html',
date:new Date(),
minify:{
removeComments:true,
collapseInlineTagWhitespace:te=true,
collapseWhitespace:true
}
})
],
module: {
rules: [
{
test: /\.css$/,
use: [
{ loader: "style-loader" },
{ loader: "css-loader" }
]
}
]
},
mode: 'production'
};
```

#### 在控制臺輸入`webpack` 打包
> 引入const CleanWebpackPlugin = require('clean-webpack-plugin') //刪除多余的文件
* 生成文件夾 `dist` 及其內容文件
