最近復習了一遍webpack,整理一下學習的筆記,按以下幾個模塊分析學習webpack;
- 基礎
- 前端開發(fā)工程環(huán)境搭建
- 打包bundle原理分析與實現(xiàn)
基礎
安裝方式,推薦使用npm init -y初始化配置文件,不推薦全局安裝,因為全局安裝會將項目中的webpack鎖定到指定版本,會造成不同項目中因為依賴版本問題,導致沖突;
使用npx 方式構建,ta會自動查找當前依賴包中的可執(zhí)行文件,如果找不到,就會去 PATH 里找。如果依然找不到,就會幫你安裝,原理就是通過shell腳本在node_modules/.bin的目錄下創(chuàng)建了一個軟連接。
基礎部分就是針對配置文件中常見的api字段解釋,例如entry 、output都是字面意思,就不過多贅述了。
const path = require("path");
module.exports = {
// 必填 webpack執(zhí)行構建入口
entry: "./src/index.js",
output: {
filename: "main.js", //將所有依賴的模塊合并輸出到main.js
path: path.resolve(__dirname, "./dist") // 輸出文件的存放路徑,必須是絕對路徑
} };
翻看筆記的時候,注意到對loader的處理這塊兒加粗強調了一下,平時每個項目的loader基本都是復制粘貼,只知其一,不知其二,原來在loader的配置,loader的順序,也是有講究的,比如 "use: ["style-loader", "css-loader","less-loader"]",就從后像前css-loader接收less-loader處理less語法轉換成css返回給css-loader,css-loader再把返回值給style-loader,做行內(nèi)樣式;
還有fie-loader中有的功能,url-loader中都有, url-loader中可以把圖片轉成base64, limit字段來決定是否需要轉換;
給文件配置hash / changehash / contenthash 的區(qū)別是什么? 答: hash作用于整個項目,chunkhash 作用于chunk,contenthash 作用于內(nèi)容;
擴展:如何自己編寫一個Loader?
Loader就是一個函數(shù),聲明式函數(shù),不能用箭頭函數(shù),拿到源代碼,作進一步的修飾處理,再返回處理后的源碼。
//創(chuàng)建一個簡單替換文本的loader文件 replace-loader.js
module.exports = function (source) {
return source.replace("hello", "您好");
};
//在webpack.config.js中引入
...,
resolveLoader: {
modules: ["./node_modules", "./myLoaders"],
},
module:{
rules:[
{
rules: [
{
test: /\.js$/,
use: [
{
loader: path.resolve(__dirname, './loader/replaceLoader.js'),
options: {
name: '開課吧',
},
},
],
},
],
}
//在處理js文件的時候,就會將hello替換為您好
另外關于plugins,我也是一直一知半解,只記了幾個常用的plugin:
HtmlWebpackPlugin : 會在打包結束后,自動生成一個html文件,并把打包生成的js模塊引入到該html 中,接收一個對象參數(shù),可以設置title,filename等;
clean-webpack-plugin:我們都知道是情況dist目錄下文件,那么如何做到某個文件或目錄不被清空呢?答:使用配置項:cleanOnceBeforeBuildPatterns 案例:cleanOnceBeforeBuildPatterns: ["/", "!dll", "!dll/"], !感 嘆號相當于exclude 排除,意思是清空操作排除dll目錄,和dll目錄下所有文件。 注意:數(shù)組列表里的 “/”是默認值,不可忽略,否則不做清空操作。
如何實現(xiàn)一個plugin?
webpack在編譯代碼過程中生命周期概念對應不同的打包階段,plugin本質上是一個類,結尾處代碼。
webpack的打包流程
1.拿到配置,初始化工作 最終配置 2.實例化一個compiler類,注冊插件,對應的生命周期綁定相應的時間 3.執(zhí)行編譯,compiler.run()
前端開發(fā)工程環(huán)境搭建
在這個板塊里,我們已經(jīng)了解了webpack項目的初始化工程搭建和簡單的api,那么一個完整的項目都還有一些什么常見到的配置文件呢
.npmrc算一個,為項目設置鏡像源,防止別人同事共建你的項目時,再去手動設置;//registry=https://registry.npm.taobao.org/
.bablelrc babel處理js的工具,值有env(負責處理原生js 比如let const 箭頭函數(shù)) / react(支持jsx to js) 等 。
postcss.config.js 他主要功能只有兩個:第一就是把css解析成JS可以操作的抽象語法樹AST,第二就是調用插 件來處理AST并得到結果;所以postcss一般都是通過插件來處理css,并不會直接處理 比如:自動補?瀏覽器前綴: autoprefixer css壓縮等 cssnano
webpack.config.js:
- sourceMap:源代碼與打包后的代碼的關系映射,devtool的值有none,還有source-map,配置后會打包出.map文件,還有’inline-source-map’, 是將映射的值直接寫在關聯(lián)的文件中
- webpack-dev-server:開發(fā)環(huán)境下提升開發(fā)效率的神器,熱更新,自動打開瀏覽器,用硬件保存的方式,保存在內(nèi)存中
- proxy:設置服務器代理,本地mock,解決跨域;
// npm i express -D
// 創(chuàng)建一個server.js 修改scripts "server":"node server.js"
//server.js
const express = require('express')
const app = express()
app.get('/api/info', (req, res) => {
res.json({
name: '開課吧',
age: 5,
msg: '歡迎來到開課吧學習前端高級課程',
})
})
app.listen('9092')
//node server.js
============
//npm i axios -D
//index.js
import axios from 'axios'
axios.get('http://localhost:9092/api/info').then(res=>{
console.log(res) })
//會有跨域問題,配置
proxy: {
"/api": {
target: "http://localhost:9092" }
}
//將index.js中get的路徑參數(shù)修改為‘/api/info’;
打包bundle原理分析與實現(xiàn)
接收webpack配置之后,進行讀取,從入口文件開始分析,哪些是依賴模塊,以及依賴模塊的位置,內(nèi)容,對內(nèi)容處理,處理成瀏覽器正確解析的內(nèi)容,遞歸處理其他的依賴模塊,生成chunk片段,依據(jù)出口配置,生成資源文件的名稱和位置;
實現(xiàn)模塊依賴分析函數(shù),核心功能,根據(jù)入口模塊開始分析依賴路徑,對內(nèi)容進行處理,支持es6+ To es5的語法轉換,返回模塊 路徑,依賴,和相應處理。
創(chuàng)建一個文件夾 webpack-simple
npm init -y
touch bundle.js
mkdir dist 和 lib src目錄
在src下創(chuàng)建a.js b.js index.js 并且模塊間有依賴關系(暫時不考慮互相依賴的情況)
//index.js
import {a} from "./a.js";
console.log(`hello ${a} webpack bundle!!`)
//a.js
import from './b.js'
export const a = `kkb $`
//b.js
export const b = '!!!'
在lib目錄下創(chuàng)建webpack.js文件,dist目錄下創(chuàng)建main.js作為導出文件,首先我們先配置webpack.config.js
const path = require("path");
module.exports = {
entry: "./src/index.js",
output: {
path: path.resolve(__dirname, "./dist"),
filename: "main.js",
},
mode: "development",
};
//bundle.js 作為啟動文件
const webpack = require('./lib/webpack.js');
const options = require('./webpack.config.js');
new webpack(options).run();
接下來就是我們的核心分析文件webpack.js
大致分為7個步驟
在webpack.js中 實現(xiàn)一個webpakc的類
- 拿到配置的入口 entryFile
- 進入到模塊拿到模塊的內(nèi)容:
- 借助node的讀取文件內(nèi)容模塊(readFileSync) const fs = require(‘fs’); fs.readFileSync(entryFile, ‘a(chǎn)ft-8’)
- 借助@babel/parser 分析模塊的內(nèi)容,parser.parse 會解析出每行代碼的node類型,但是實際工作中會有很多行代碼,不方便遍歷查詢 :代碼 const ast = parser.parse( content, { sourceType: “module”}) console.log(ast.program.body)
- 對語法樹做增刪改查的 @babel/traverse: travaerse( ast,{ ImportDeclaration(node){ console.log( node.source.value) } } ) //ImportDeclaration節(jié)點類型
- 使用path.dirname獲取入口文件的路徑,和文件的名稱做拼接
- 使用@bable/core 處理內(nèi)容 const { code } = transformFromAst(ast,null , { presets: [“@babel/preset-env” ] }) 返回code
- 在parse方法里,拿到返回的數(shù)據(jù)結構{ entryFile, yilai , code }
- 遞歸處理模塊里的依賴模塊
- 對數(shù)據(jù)結構進行轉換
- 生成bundle文件 (從outpaut的配置字段里拿到文件的存儲位置和文件的名稱)
- 借助fs.writeFileSync來生成bundle文件 fs.writeFileSync( bundlePath,content,”utf-8”) 要對content進行序列化
const fs = require('fs');
const parser = require('@babel/parser');
const travaerse = require('@babel/traverse').default;
const path = require('path');
const { transformFromAst } = require('@babel/core');
//創(chuàng)建一個webpack類
module.exports = class webpack {
constructor(options){
//這里的options參數(shù)就是我們配置文件的參數(shù),我們先把entry,output保存下來
const {entry,output} = options;
this.entry = entry;
this.output = output;
this.modules = []
}
run(){
//入口函數(shù)
const info = this.parse(this.entry);
this.modules.push(info);
//遞歸處理
//用雙層for 循環(huán) 遍歷modules,達到遞歸的效果
for(let i =0; i< this.modules.length; i ++){
const item = this.modules[i];
const yilai = item.yilai;
if(yilai){
for(let j in yilai){
this.modules.push(this.parse(yilai[j]))
}
}
}
//數(shù)據(jù)格式轉換 arr to obj
const obj = {}
this.modules.forEach((item) => {
obj[item.entryFile] = {
yilai : item.yilai,
code : item.code
}
})
this.file(obj);
}
parse(entryFile){
//解析模塊 將模塊信息返回
const content = fs.readFileSync(entryFile,'utf-8')
const ast = parser.parse(content, {
sourceType:"module"
});
const yilai = {};
//對抽象語法樹做增刪改查的過濾
travaerse(ast, {
//把類型作為函數(shù)名稱
ImportDeclaration({node}) {
const newPathName = './' + path.join(path.dirname(entryFile), node.source.value);
yilai[node.source.value] = newPathName;
}
})
//拿到依賴信息之后,對內(nèi)容做分析
const {code} = transformFromAst(ast,null,{
presets:["@babel/preset-env"]
})
return{
entryFile,
yilai,
code
}
}
file(obj){
//1.生成bundle文件(需要從outpaut的配置字段里拿到文件的存儲位置和文件的名稱)
//通過拼接得到一個絕對路徑
const bundlePath = path.join(this.output.path, this.output.filename);
const newObj = JSON.stringify(obj);
const content = `(function(modules){
function require(module){
// ./a.js ---> 是否可以拿到這個模塊的code?
function newRequire(relativePath){
// 就是把相對于入口模塊的路徑替換成相對根目錄的路徑
return require(modules[module].yilai[relativePath])
}
const exports = {};
(function(exports,require,code){
eval(code)
})(exports,newRequire,modules[module].code)
return exports;
}
require('${this.entry}')
})(${newObj})`
fs.writeFileSync(bundlePath, content, "utf-8");
}
}
接下來node bundle.js 運行起來
我們會看到生成的dist/main.js中
(function(modules){
function require(module){
// ./a.js ---> 是否可以拿到這個模塊的code?
function newRequire(relativePath){
// 就是把相對于入口模塊的路徑替換成相對根目錄的路徑
return require(modules[module].yilai[relativePath])
}
const exports = {};
(function(exports,require,code){
eval(code)
})(exports,newRequire,modules[module].code)
return exports;
}
require('./src/index.js')
})({"./src/index.js":{"yilai":{"./a.js":"./src/a.js"},"code":"\"use strict\";\n\nvar _a = require(\"./a.js\");\n\nconsole.log(\"hello \".concat(_a.a, \" webpack bundle!!\"));"},"./src/a.js":{"yilai":{"./b.js":"./src/b.js"},"code":"\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.a = void 0;\n\nvar _b = require(\"./b.js\");\n\nvar a = \"kkb \".concat(_b.b);\nexports.a = a;"},"./src/b.js":{"yilai":{},"code":"\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.b = void 0;\nvar b = '!!!';\nexports.b = b;"}})
就可以直接在瀏覽器中運行了。