前言

大家好,我是林三心,题目腾讯面试官:同学,你说你会Webpack,那说说他的原理?,是本菜鸟在面试腾讯时,面试官说的问的原话,一字不差,哈哈。本菜鸟过后必定是答复不上来,最初也挂了。明天就简略实现一下webpack的打包原理,并分享给大家吧。因为webpack原理是非常复杂的,所以明天咱们只是简略实现哦。

原理图解

  • 1、首先必定是要先解析入口文件entry,将其转为AST(形象语法树),应用@babel/parser
  • 2、而后应用@babel/traverse去找出入口文件所有依赖模块
  • 3、而后应用@babel/core+@babel/preset-env将入口文件的AST转为Code
  • 4、将2中找到的入口文件的依赖模块,进行遍历递归,反复执行1,2,3
  • 5。重写require函数,并与4中生成的递归关系图一起,输入到bundle

代码实现

webpack具体实现原理是很简单的,这里只是简略实现一下,让大家粗略理解一下,webpack是怎么运作的。在代码实现过程中,大家能够本人console.log一下,看看ast,dependcies,code这些具体长什么样,我这里就不展现了,本人去看会比拟有成就感,嘿嘿!!

目录

config.js

这个文件中模仿webpack的配置

const path = require('path')module.exports = {  entry: './src/index.js',  output: {    path: path.resolve(__dirname, './dist'),    filename: 'main.js'  }}

入口文件

src/index.js是入口文件

// src/indeximport { age } from './aa.js'import { name } from './hh.js'console.log(`${name}往年${age}岁了`)// src/aa.jsexport const age = 18// src/hh.jsconsole.log('我来了')export const name = '林三心'

1. 定义Compiler类

// index.jsclass Compiler {  constructor(options) {    // webpack 配置    const { entry, output } = options    // 入口    this.entry = entry    // 进口    this.output = output    // 模块    this.modules = []  }  // 构建启动  run() {}  // 重写 require函数,输入bundle  generate() {}}

2. 解析入口文件,获取 AST

咱们这里应用@babel/parser,这是babel7的工具,来帮忙咱们剖析外部的语法,包含 es6,返回一个 AST 形象语法树

const fs = require('fs')const parser = require('@babel/parser')const options = require('./webpack.config')const Parser = {  getAst: path => {    // 读取入口文件    const content = fs.readFileSync(path, 'utf-8')    // 将文件内容转为AST形象语法树    return parser.parse(content, {      sourceType: 'module'    })  }}class Compiler {  constructor(options) {    // webpack 配置    const { entry, output } = options    // 入口    this.entry = entry    // 进口    this.output = output    // 模块    this.modules = []  }  // 构建启动  run() {    const ast = Parser.getAst(this.entry)  }  // 重写 require函数,输入bundle  generate() {}}new Compiler(options).run()

3. 找出所有依赖模块

Babel 提供了@babel/traverse(遍历)办法保护这 AST 树的整体状态,咱们这里应用它来帮咱们找出依赖模块

const fs = require('fs')const path = require('path')const options = require('./webpack.config')const parser = require('@babel/parser')const traverse = require('@babel/traverse').defaultconst Parser = {  getAst: path => {    // 读取入口文件    const content = fs.readFileSync(path, 'utf-8')    // 将文件内容转为AST形象语法树    return parser.parse(content, {      sourceType: 'module'    })  },  getDependecies: (ast, filename) => {    const dependecies = {}    // 遍历所有的 import 模块,存入dependecies    traverse(ast, {      // 类型为 ImportDeclaration 的 AST 节点 (即为import 语句)      ImportDeclaration({ node }) {        const dirname = path.dirname(filename)        // 保留依赖模块门路,之后生成依赖关系图须要用到        const filepath = './' + path.join(dirname, node.source.value)        dependecies[node.source.value] = filepath      }    })    return dependecies  }}class Compiler {  constructor(options) {    // webpack 配置    const { entry, output } = options    // 入口    this.entry = entry    // 进口    this.output = output    // 模块    this.modules = []  }  // 构建启动  run() {    const { getAst, getDependecies } = Parser    const ast = getAst(this.entry)    const dependecies = getDependecies(ast, this.entry)  }  // 重写 require函数,输入bundle  generate() {}}new Compiler(options).run()

4. AST 转换为 code

AST 语法树转换为浏览器可执行代码,咱们这里应用@babel/core 和 @babel/preset-env

const fs = require('fs')const path = require('path')const options = require('./webpack.config')const parser = require('@babel/parser')const traverse = require('@babel/traverse').defaultconst { transformFromAst } = require('@babel/core')const Parser = {  getAst: path => {    // 读取入口文件    const content = fs.readFileSync(path, 'utf-8')    // 将文件内容转为AST形象语法树    return parser.parse(content, {      sourceType: 'module'    })  },  getDependecies: (ast, filename) => {    const dependecies = {}    // 遍历所有的 import 模块,存入dependecies    traverse(ast, {      // 类型为 ImportDeclaration 的 AST 节点 (即为import 语句)      ImportDeclaration({ node }) {        const dirname = path.dirname(filename)        // 保留依赖模块门路,之后生成依赖关系图须要用到        const filepath = './' + path.join(dirname, node.source.value)        dependecies[node.source.value] = filepath      }    })    return dependecies  },  getCode: ast => {    // AST转换为code    const { code } = transformFromAst(ast, null, {      presets: ['@babel/preset-env']    })    return code  }}class Compiler {  constructor(options) {    // webpack 配置    const { entry, output } = options    // 入口    this.entry = entry    // 进口    this.output = output    // 模块    this.modules = []  }  // 构建启动  run() {    const { getAst, getDependecies, getCode } = Parser    const ast = getAst(this.entry)    const dependecies = getDependecies(ast, this.entry)    const code = getCode(ast)  }  // 重写 require函数,输入bundle  generate() {}}new Compiler(options).run()

5. 递归解析所有依赖项,生成依赖关系图

const fs = require('fs')const path = require('path')const options = require('./webpack.config')const parser = require('@babel/parser')const traverse = require('@babel/traverse').defaultconst { transformFromAst } = require('@babel/core')const Parser = {  getAst: path => {    // 读取入口文件    const content = fs.readFileSync(path, 'utf-8')    // 将文件内容转为AST形象语法树    return parser.parse(content, {      sourceType: 'module'    })  },  getDependecies: (ast, filename) => {    const dependecies = {}    // 遍历所有的 import 模块,存入dependecies    traverse(ast, {      // 类型为 ImportDeclaration 的 AST 节点 (即为import 语句)      ImportDeclaration({ node }) {        const dirname = path.dirname(filename)        // 保留依赖模块门路,之后生成依赖关系图须要用到        const filepath = './' + path.join(dirname, node.source.value)        dependecies[node.source.value] = filepath      }    })    return dependecies  },  getCode: ast => {    // AST转换为code    const { code } = transformFromAst(ast, null, {      presets: ['@babel/preset-env']    })    return code  }}class Compiler {  constructor(options) {    // webpack 配置    const { entry, output } = options    // 入口    this.entry = entry    // 进口    this.output = output    // 模块    this.modules = []  }  // 构建启动  run() {    // 解析入口文件    const info = this.build(this.entry)    this.modules.push(info)    this.modules.forEach(({ dependecies }) => {      // 判断有依赖对象,递归解析所有依赖项      if (dependecies) {        for (const dependency in dependecies) {          this.modules.push(this.build(dependecies[dependency]))        }      }    })    // 生成依赖关系图    const dependencyGraph = this.modules.reduce(      (graph, item) => ({        ...graph,        // 应用文件门路作为每个模块的惟一标识符,保留对应模块的依赖对象和文件内容        [item.filename]: {          dependecies: item.dependecies,          code: item.code        }      }),      {}    )  }  build(filename) {    const { getAst, getDependecies, getCode } = Parser    const ast = getAst(filename)    const dependecies = getDependecies(ast, filename)    const code = getCode(ast)    return {      // 文件门路,能够作为每个模块的惟一标识符      filename,      // 依赖对象,保留着依赖模块门路      dependecies,      // 文件内容      code    }  }  // 重写 require函数,输入bundle  generate() {}}new Compiler(options).run()

6. 重写 require 函数,输入 bundle

const fs = require('fs')const path = require('path')const options = require('./webpack.config')const parser = require('@babel/parser')const traverse = require('@babel/traverse').defaultconst { transformFromAst } = require('@babel/core')const Parser = {  getAst: path => {    // 读取入口文件    const content = fs.readFileSync(path, 'utf-8')    // 将文件内容转为AST形象语法树    return parser.parse(content, {      sourceType: 'module'    })  },  getDependecies: (ast, filename) => {    const dependecies = {}    // 遍历所有的 import 模块,存入dependecies    traverse(ast, {      // 类型为 ImportDeclaration 的 AST 节点 (即为import 语句)      ImportDeclaration({ node }) {        const dirname = path.dirname(filename)        // 保留依赖模块门路,之后生成依赖关系图须要用到        const filepath = './' + path.join(dirname, node.source.value)        dependecies[node.source.value] = filepath      }    })    return dependecies  },  getCode: ast => {    // AST转换为code    const { code } = transformFromAst(ast, null, {      presets: ['@babel/preset-env']    })    return code  }}class Compiler {  constructor(options) {    // webpack 配置    const { entry, output } = options    // 入口    this.entry = entry    // 进口    this.output = output    // 模块    this.modules = []  }  // 构建启动  run() {    // 解析入口文件    const info = this.build(this.entry)    this.modules.push(info)    this.modules.forEach(({ dependecies }) => {      // 判断有依赖对象,递归解析所有依赖项      if (dependecies) {        for (const dependency in dependecies) {          this.modules.push(this.build(dependecies[dependency]))        }      }    })    // 生成依赖关系图    const dependencyGraph = this.modules.reduce(      (graph, item) => ({        ...graph,        // 应用文件门路作为每个模块的惟一标识符,保留对应模块的依赖对象和文件内容        [item.filename]: {          dependecies: item.dependecies,          code: item.code        }      }),      {}    )    this.generate(dependencyGraph)  }  build(filename) {    const { getAst, getDependecies, getCode } = Parser    const ast = getAst(filename)    const dependecies = getDependecies(ast, filename)    const code = getCode(ast)    return {      // 文件门路,能够作为每个模块的惟一标识符      filename,      // 依赖对象,保留着依赖模块门路      dependecies,      // 文件内容      code    }  }  // 重写 require函数 (浏览器不能辨认commonjs语法),输入bundle  generate(code) {    // 输入文件门路    const filePath = path.join(this.output.path, this.output.filename)    // 懵逼了吗? 没事,下一节咱们捋一捋    const bundle = `(function(graph){      function require(module){        function localRequire(relativePath){          return require(graph[module].dependecies[relativePath])        }        var exports = {};        (function(require,exports,code){          eval(code)        })(localRequire,exports,graph[module].code);        return exports;      }      require('${this.entry}')    })(${JSON.stringify(code)})`    // 把文件内容写入到文件系统    fs.writeFileSync(filePath, bundle, 'utf-8')  }}new Compiler(options).run()

7. 看看main里的代码

实现了下面的代码,也就实现了把打包后的代码写到main.js文件里,咱们来看看那main.js文件里的代码吧:

(function(graph){      function require(module){        function localRequire(relativePath){          return require(graph[module].dependecies[relativePath])        }        var exports = {};        (function(require,exports,code){          eval(code)        })(localRequire,exports,graph[module].code);        return exports;      }      require('./src/index.js')    })({      "./src/index.js": {          "dependecies": {              "./aa.js": "./src\\aa.js",              "./hh.js": "./src\\hh.js"          },          "code": "\"use strict\";\n\nvar _aa = require(\"./aa.js\");\n\nvar _hh = require(\"./hh.js\");\n\nconsole.log(\"\".concat(_hh.name, \"\\u4ECA\\u5E74\").concat(_aa.age, \"\\u5C81\\u4E86\"));"      },      "./src\\aa.js": {          "dependecies": {},          "code": "\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n  value: true\n});\nexports.age = void 0;\nvar age = 18;\nexports.age = age;"      },      "./src\\hh.js": {          "dependecies": {},          "code": "\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n  value: true\n});\nexports.name = void 0;\nconsole.log('我来了');\nvar name = '林三心';\nexports.name = name;"      }  })

大家能够执行一下main.js的代码,输入后果是:

我来了林三心往年18岁了

结语

我是林三心,一个热心的前端菜鸟程序员。如果你上进,喜爱前端,想学习前端,那咱们能够交朋友,一起摸鱼哈哈,摸鱼群,加我请备注【思否】