什麼是webpack
webpack 是一個現代 JavaScript 應用程式的靜態模組打包器(module bundler)。當 webpack 處理應用程式時,它會遞迴地構建一個依賴關係圖(dependency graph),其中包含應用程式需要的每個模組,然後將所有這些模組打包成一個或多個 bundle
可以做的事情
程式碼轉換、檔案優化、程式碼分割、模組合併、自動重新整理、程式碼校驗、自動釋出
複製程式碼
需要提前掌握的內容
- 需要node基礎,以及npm的使用
- 掌握es6語法
主要學習webpack哪些內容
- webpack常見配置
- webpack高階配置
- webpack優化策略
- ast抽象語法樹
- webpack中的Tapable
- 掌握webpack流程,手寫webpack
- 手寫webpack中常見的loader
- 手寫webpack中常見的plugin
建立檔案
mkdir webpack-test && cd webpack-test
mkdir src
touch src/index.js
複製程式碼

初始化檔案
npm init -y 初始檔案(預設的)
npm init
複製程式碼
開始打包
npx webpack
複製程式碼


配置webpack.config.js
touch webpack.config.js
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
devServer: { // 開發伺服器的配置
contentBase: path.join(__dirname, 'dist'),
compress: true,
port: 3000
},
mode: 'development', // 模式 預設兩種production development
entry: './src/index.js', //入口
output: {
filename: 'bundle.js', //打包後的檔名
path: path.resolve(__dirname, 'dist'), //路徑必須是一個絕對路徑
},
plugins: [// 陣列放著所有的webpack外掛
new HtmlWebpackPlugin({
template: './src/index.html',
filename: 'index.html'
})
]
}
複製程式碼
pagkage.js
"dev": "webpack-dev-server"
複製程式碼
index.js
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div id="root"></div>
<script src="bundle.js"></script>
</body>
</html>
複製程式碼
index.js
var root = document.getElementById("root");
root.innerHTML="你好"
複製程式碼
目前的目錄

啟動專案
npm run dev
複製程式碼

瀏覽器輸入http://localhost:3000/
