目录
简易版webpack的实现步骤
1、npm的bin
* npm init -y
* package.json添加配置
########
{
"bin": {
"llpack": "bin/index.js"
}
}
########
入口文件头部添加
########
#!/usr/bin/env node
########
* npm link
2、文件的读写
const path = require("path")
const fs = require("fs")
const entry = path.resolve('./src/main.js')
const output = path.resolve('./dist/index.js')
const scriptStr = fs.readFileSync(entry, "utf-8")
fs.writeFileSync(output, scriptStr)
3、webpack是如何做的
* npm i webpack webpack-cli -D
* package.json
########
{
"scripts": {
"build": "webpack --config webpack.config.js"
}
}
########
* webpack.config.js
########
const path = require('path');
module.exports = {
entry: './src/main.js',
output: {
path: path.resolve(__dirname, './dist'),
filename: 'index.js'
},
mode: "development"
};
########
(() => {
var modules = {
"./src/main.js":
((module) => {
eval("const {recursionFunc} = require(\"./src/utils.js\")\r\n\r\nconsole.log(recursionFunc)\r\n\n\n");
}),
"./src/utils.js":
((module) => {
eval("module.exports = {\r\n recursionFunc: \"递归函数\"\r\n}\r\n\n\n");
})
};
var modulesCache = {};
function require(path) {
if (modulesCache[path]) {
return modulesCache[path].exports;
}
modulesCache[path] = {
exports: {}
};
modules[path](modulesCache[path]);
return modulesCache[path].exports;
}
require("./src/main.js");
})();
4、模块遍历(图结构)
const path = require("path")
const fs = require("fs")
const modules = {}
function recursionFun(filePath) {
modules[filePath] = fs.readFileSync(filePath, 'utf-8')
.replace(/require\(["'](.*)['"]\)/g, (str, $1) => {
const joinPath = path.join(filePath, '..', $1)
if (!modules[joinPath]) {
recursionFun(joinPath)
}
return `require('${joinPath}')`
})
}
recursionFun(path.join('./src/main.js'))
5、模块脚本拼接
const path = require("path")
const fs = require("fs")
const entry = path.join('./src/main.js')
const output = path.join('./dist/index.js')
const modules = {}
function recursionFun(filePath) {
modules[filePath] = fs.readFileSync(filePath, 'utf-8')
.replace(/require\(["'](.*)['"]\)/g, (str, $1) => {
const joinPath = path.join(filePath, '..', $1)
if (!modules[joinPath]) {
recursionFun(joinPath)
}
return `require(${JSON.stringify(joinPath)})`
})
}
recursionFun(entry)
const modulesStr = Object.keys(modules).map(moduleId => {
return `
${JSON.stringify(moduleId)}:
((module) => {
eval(${JSON.stringify(modules[moduleId])})
})
`
}).join()
const scriptStr = `
(() => {
var modules = {
${modulesStr}
};
var modulesCache = {};
function require(path) {
if (modulesCache[path]) {
return modulesCache[path].exports;
}
modulesCache[path] = {
exports: {}
};
modules[path](modulesCache[path]);
return modulesCache[path].exports;
}
require(${JSON.stringify(entry)});
})();
`
fs.writeFileSync(output, scriptStr)
标签:const,步骤,require,modules,webpack,js,简易版,modulesCache,path
From: https://www.cnblogs.com/linding/p/18055547