鲁迅说: 当咱们会用同样东西的时候,就要适当地去了解一下这个东西是怎么运转的。css
固然我不可能实现所有功能, 由于能力有限, 我只挑几个重要的实现node
建立两个项目, 一个为项目juejin-webpack
, 一个为咱们本身写的打包工具, 名字为xydpack
webpack
1)juejin-webpack
项目主入口文件内容和打包配置内容为 :web
// webpack.config.js
const path = require('path')
const root = path.join(__dirname, './')
const config = {
mode : 'development',
entry : path.join(root, 'src/app.js'),
output : {
path : path.join(root, 'dist'),
filename : 'bundle.js'
}
}
module.exports = config
复制代码
// app.js
/*
// moduleA.js
let name = 'xuyede'
module.exports = name
*/
const name = require('./js/moduleA.js')
const oH1 = document.createElement('h1')
oH1.innerHTML = 'Hello ' + name
document.body.appendChild(oH1)
复制代码
2)为了方便调试,咱们须要把本身的xydpack
包link
到本地, 而后引入到juejin-webpack
中, 具体操做以下npm
// 1. 在xydpack项目的 package.json文件中加上 bin属性, 并配置对应的命令和执行文件
{
"name": "xydpack",
"version": "1.0.0",
"main": "index.js",
"license": "MIT",
"bin": {
"xydpack" : "./bin/xydpack.js"
}
}
// 2. 在xydpack项目中添加相应路径的xydpack.js文件, 并在顶部加上该文件的运行方式
#! /usr/bin/env node
console.log('this is xydpack')
// 3. 在 xydpack项目的命令行上输入 npm link
// 4. 在 juejin-webpack项目的命令行上输入 npm link xydpack
// 5. 在 juejin-webpack项目的命令行上输入 npx xydpack后, 会输出 this is xydpack 就成功了
复制代码
从第一步的流程图中咱们能够看出, webpack
打包文件的第一步是获取打包配置文件的内容, 而后去实例化一个Compiler
类, 再经过run
去开启编译, 因此我能够把xydpack.js
修改成json
#! /usr/bin/env node
const path = require('path')
const Compiler = require('../lib/compiler.js')
const config = require(path.resolve('webpack.config.js'))
const compiler = new Compiler(config)
compiler.run()
复制代码
而后去编写compiler.js
的内容浏览器
ps : 编写xydpack
能够经过在juejin-webpack
项目中使用npx xydpack
去调试bash
根据上面的调用咱们能够知道, Compiler
为一个类, 而且有run
方法去开启编译babel
class Compiler {
constructor (config) {
this.config = config
}
run () {}
}
module.exports = Compiler
复制代码
在流程图中有一个buildModule
的方法去实现构建模块的依赖和获取主入口的路径, 因此咱们也加上这个方法app
const path = require('path')
class Compiler {
constructor (config) {
this.config = config
this.modules = {}
this.entryPath = ''
this.root = process.cwd()
}
buildModule (modulePath, isEntry) {
// modulePath : 模块路径 (绝对路径)
// isEntry : 是不是主入口
}
run () {
const { entry } = this.config
this.buildModule(path.resolve(this.root, entry), true)
}
}
module.exports = Compiler
复制代码
在buildModule
方法中, 咱们须要从主入口出发, 分别获取模块的路径以及对应的代码块, 并把代码块中的require
方法改成__webpack_require__
方法
const path = require('path')
const fs = require('fs')
class Compiler {
constructor (config) { //... }
getSource (modulePath) {
const content = fs.readFileSync(modulePath, 'utf-8')
return content
}
buildModule (modulePath, isEntry) {
// 模块的源代码
let source = this.getSource(modulePath)
// 模块的路径
let moduleName = './' + path.relative(this.root, modulePath).replace(/\\/g, '/')
if (isEntry) this.entryPath = moduleName
}
run () {
const { entry } = this.config
this.buildModule(path.resolve(this.root, entry), true)
}
}
module.exports = Compiler
复制代码
获得模块的源码后, 须要去解析,替换源码和获取模块的依赖项, 因此添加一个parse
方法去操做, 而解析代码须要如下两个步骤 :
@babel/parser -> 把源码生成AST
@babel/traverse -> 遍历AST的结点
@babel/types -> 替换AST的内容
@babel/generator -> 根据AST生成新的源码
复制代码
注意 : @babel/traverse
和@babel/generator
是ES6
的包, 须要使用default
导出
const path = require('path')
const fs = require('fs')
const parser = require('@babel/parser')
const t = require('@babel/types')
const traverse = require('@babel/traverse').default
const generator = require('@babel/generator').default
class Compiler {
constructor (config) { //... }
getSource (modulePath) { //... }
parse (source, dirname) {
// 生成AST
let ast = parser.parse(source)
// 遍历AST结点
traverse(ast, {
})
// 生成新的代码
let sourceCode = generator(ast).code
}
buildModule (modulePath, isEntry) {
let source = this.getSource(modulePath)
let moduleName = './' + path.relative(this.root, modulePath).replace(/\\/g, '/')
if (isEntry) this.entryPath = moduleName
this.parse(source, path.dirname(moduleName))
}
run () {
const { entry } = this.config
this.buildModule(path.resolve(this.root, entry), true)
}
}
module.exports = Compiler
复制代码
那么获得的ast
是什么呢, 你们能够去 AST Explorer 查看代码解析成ast
后是什么样子。
当有函数调用的语句相似require()/ document.createElement()/ document.body.appendChild()
, 会有一个CallExpression
的属性保存这些信息, 因此接下来要干的事为 :
require
, 因此要作一层判断path
的目录名const path = require('path')
const fs = require('fs')
const parser = require('@babel/parser')
const t = require('@babel/types')
const traverse = require('@babel/traverse').default
const generator = require('@babel/generator').default
class Compiler {
constructor (config) { //... }
getSource (modulePath) { //... }
parse (source, dirname) {
// 生成AST
let ast = parser.parse(source)
// 模块依赖项列表
let dependencies = []
// 遍历AST结点
traverse(ast, {
CallExpression (p) {
const node = p.node
if (node.callee.name === 'require') {
// 函数名替换
node.callee.name = '__webpack_require__'
// 路径替换
let modulePath = node.arguments[0].value
if (!path.extname(modulePath)) {
// require('./js/moduleA')
throw new Error(`没有找到文件 : ${modulePath} , 检查是否加上正确的文件后缀`)
}
modulePath = './' + path.join(dirname, modulePath).replace(/\\/g, '/')
node.arguments = [t.stringLiteral(modulePath)]
// 保存模块依赖项
dependencies.push(modulePath)
}
}
})
// 生成新的代码
let sourceCode = generator(ast).code
return {
sourceCode, dependencies
}
}
buildModule (modulePath, isEntry) {
let source = this.getSource(modulePath)
let moduleName = './' + path.relative(this.root, modulePath).replace(/\\/g, '/')
if (isEntry) this.entryPath = moduleName
let { sourceCode, dependencies } = this.parse(source, path.dirname(moduleName))
}
run () {
const { entry } = this.config
this.buildModule(path.resolve(this.root, entry), true)
}
}
module.exports = Compiler
复制代码
递归获取全部的模块依赖, 并保存全部的路径与依赖的模块
const path = require('path')
const fs = require('fs')
const parser = require('@babel/parser')
const t = require('@babel/types')
const traverse = require('@babel/traverse').default
const generator = require('@babel/generator').default
class Compiler {
constructor (config) { //... }
getSource (modulePath) { //... }
parse (source, dirname) { //... }
buildModule (modulePath, isEntry) {
let source = this.getSource(modulePath)
let moduleName = './' + path.relative(this.root, modulePath).replace(/\\/g, '/')
if (isEntry) this.entryPath = moduleName
let { sourceCode, dependencies } = this.parse(source, path.dirname(moduleName))
this.modules[moduleName] = JSON.stringify(sourceCode)
dependencies.forEach(d => this.buildModule(path.join(this.root, d)), false)
}
run () {
const { entry } = this.config
this.buildModule(path.resolve(this.root, entry), true)
}
}
module.exports = Compiler
复制代码
在获取了全部的模块依赖关系和主入口后, 接下来要把数据插入模板并写入配置项中的output.path
由于须要一个模板, 因此借用一下webpack
的模板, 使用EJS
去生成模板, 不了解EJS
的点这里, 模板的内容为 :
// lib/template.ejs
(function (modules) {
var installedModules = {};
function __webpack_require__(moduleId) {
if (installedModules[moduleId]) {
return installedModules[moduleId].exports;
}
var module = installedModules[moduleId] = {
i: moduleId,
l: false,
exports: {}
};
modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
module.l = true;
return module.exports;
}
return __webpack_require__(__webpack_require__.s = "<%-entryPath%>");
})
({
<%for (const key in modules) {%>
"<%-key%>":
(function (module, exports, __webpack_require__) {
eval(<%-modules[key]%>);
}),
<%}%>
});
复制代码
下面咱们编写emit
函数
const path = require('path')
const fs = require('fs')
const parser = require('@babel/parser')
const t = require('@babel/types')
const traverse = require('@babel/traverse').default
const generator = require('@babel/generator').default
const ejs = require('ejs')
class Compiler {
constructor (config) { //... }
getSource (modulePath) { //... }
parse (source, dirname) { //... }
buildModule (modulePath, isEntry) { //... }
emit () {
const { modules, entryPath } = this
const outputPath = path.resolve(this.root, this.config.output.path)
const filePath = path.resolve(outputPath, this.config.output.filename)
if (!fs.readdirSync(outputPath)) {
fs.mkdirSync(outputPath)
}
ejs.renderFile(path.join(__dirname, 'template.ejs'), { modules, entryPath })
.then(code => {
fs.writeFileSync(filePath, code)
})
}
run () {
const { entry } = this.config
this.buildModule(path.resolve(this.root, entry), true)
this.emit()
}
}
module.exports = Compiler
复制代码
若是写到这, 在juejin-webpack
项目里输入npx xydpack
就会生成一个dist
目录, 里面有一个bundle.js
文件, 可运行在浏览器中, 演示
通过二以后, 只是单纯地转了一下代码, 好像没啥意义~
因此咱们要加上loader
, 对loader
不熟悉的点 这里 , 由于是手写嘛, 因此咱们loader
也本身写一下
注意 : 由于这个东西至关简易, 因此只能玩一下样式的loader
, 其余的玩不了, 因此只演示写一下样式的loader
我我的习惯使用stylus
去编写样式, 因此样式就写stylus-loader
和style-loader
首先, 在配置项上加上loader
, 而后在app.js
中引入init.styl
// webpack.config.js
const path = require('path')
const root = path.join(__dirname, './')
const config = {
mode : 'development',
entry : path.join(root, 'src/app.js'),
output : {
path : path.join(root, 'dist'),
filename : 'bundle.js'
},
module : {
rules : [
{
test : /\.styl(us)?$/,
use : [
path.join(root, 'loaders', 'style-loader.js'),
path.join(root, 'loaders', 'stylus-loader.js')
]
}
]
}
}
module.exports = config
-----------------------------------------------------------------------------------------
// app.js
const name = require('./js/moduleA.js')
require('./style/init.styl')
const oH1 = document.createElement('h1')
oH1.innerHTML = 'Hello ' + name
document.body.appendChild(oH1)
复制代码
在根目录建立一个loaders
目录去编写咱们的loader
// stylus-loader
const stylus = require('stylus')
function loader (source) {
let css = ''
stylus.render(source, (err, data) => {
if (!err) {
css = data
} else {
throw new Error(error)
}
})
return css
}
module.exports = loader
-----------------------------------------------------------------------------------------
// style-loader
function loader (source) {
let script = `
let style = document.createElement('style')
style.innerHTML = ${JSON.stringify(source)}
document.body.appendChild(style)
`
return script
}
module.exports = loader
复制代码
loader
是在读取文件的时候进行操做的, 所以修改compiler.js
, 在getSource
函数加上对应的操做
const path = require('path')
const fs = require('fs')
const parser = require('@babel/parser')
const t = require('@babel/types')
const traverse = require('@babel/traverse').default
const generator = require('@babel/generator').default
const ejs = require('ejs')
class Compiler {
constructor (config) { //... }
getSource (modulePath) {
try {
let rules = this.config.module.rules
let content = fs.readFileSync(modulePath, 'utf-8')
for (let i = 0; i < rules.length; i ++) {
let { test, use } = rules[i]
let len = use.length - 1
if (test.test(modulePath)) {
// 递归处理全部loader
function loopLoader () {
let loader = require(use[len--])
content = loader(content)
if (len >= 0) {
loopLoader()
}
}
loopLoader()
}
}
return content
} catch (error) {
throw new Error(`获取数据错误 : ${modulePath}`)
}
}
parse (source, dirname) { //... }
buildModule (modulePath, isEntry) { //... }
emit () { //... }
run () { //... }
}
module.exports = Compiler
复制代码
而后运行npx xydpack
打包, 会添加一段这样的代码
"./src/style/init.styl":
(function (module, exports, __webpack_require__) {
eval("let style = document.createElement('style');\nstyle.innerHTML = \"* {\\n padding: 0;\\n margin: 0;\\n}\\nbody {\\n color: #f40;\\n}\\n\";\ndocument.head.appendChild(style);");
}),
复制代码
而后运行就能够了, 演示
脚本的loader
, 第一个想到的就是babel-loader
, 咱们本身写一个babel-loader
, 可是须要使用webpack
去打包, 修改配置文件为
// webpack.config.js
resolveLoader : {
modules : ['node_modules', path.join(root, 'loaders')]
},
module : {
rules : [
{
test : /\.js$/,
use : {
loader : 'babel-loader',
options : {
presets : [
'@babel/preset-env'
]
}
}
}
]
}
复制代码
使用babel
须要三个包: @babel/core | @babel/preset-env | loader-utils
安装后, 而后编写babel-loader
const babel = require('@babel/core')
const loaderUtils = require('loader-utils')
function loader (source) {
let options = loaderUtils.getOptions(this)
let cb = this.async();
babel.transform(source, {
...options,
sourceMap : true,
filename : this.resourcePath.split('/').pop(),
}, (err, result) => {
// 错误, 返回的值, sourceMap的内容
cb(err, result.code, result.map)
})
}
module.exports = loader
复制代码
而后使用webpack
打包就好了
到这里, 咱们就能够大概猜一下webpack
的运做流程是这样的 :
注意 : 我这个只是本身闹着玩的, 要学webpack
, 点 这里
ps : 立刻毕业而后失业了, 有没有哪家公司缺页面仔的请联系我, 切图也行的, 我很耐造
邮箱 : will3virgo@163.com