銜接上文,到目前為止我們已經(jīng)能夠獲取變更文件路徑,支持loader,插件,增量打包了,那自然應(yīng)該找個(gè)npm包試一試功能,此處我選擇moment,在moment入口文件同樣require其他依賴文件,這樣可以測(cè)試整個(gè)require鏈路是否生效。
思路
- 根據(jù)nodejs解析路徑寫一個(gè)函數(shù)
- 輸入為絕對(duì)路徑、相對(duì)路徑、node_modules路徑
思考
- node引入包長(zhǎng)分為三種:絕對(duì)路徑、相對(duì)路徑、node_modules路徑
- node_modules路徑規(guī)則為:
1.到目錄下找js文件
2.找該目錄下的package.json,讀取其main獲取路徑
3.尋找該目錄下的index.js
4.都找不到則向上尋找,直到根路徑
實(shí)現(xiàn)
此處寫法不嚴(yán)謹(jǐn),僅僅判斷了window 頂層路徑有CDEF等盤
const getFilePath = (path) => {
if (/^\w+$/g.test(path)) {
const initPath = join(__dirname, "../", "node_modules", path);
if (
fs.existsSync(initPath) &&
fs.existsSync(join(initPath, "package.json"))
) {
const { main } = JSON.parse(
fs.readFileSync(join(initPath, "package.json"))
);
if (fs.existsSync(initPath)) return join(initPath, main);
} else {
let curPath = initPath;
const isRoot = /[A-Z]\:\\/.test(curPath);
while (!isRoot && !fs.existsSync(`${curPath}.js`)) {
curPath = join(curPath, "../");
}
return curPath;
}
}
// 絕對(duì)路徑, 相對(duì)路徑
return resolve(path);
};
index.js
const moment = require("moment");
document.write(moment());
打包結(jié)果bundle.js
由于commonjs打包把整個(gè)moment包都打進(jìn)來了,所以此不做展示

1646583151(1).png
頁面效果

1646583288(1).png
至此,我們的nodejs引入包基本沒有問題了,變可以開開心心開發(fā)熱更新插件了