关于前端:腾讯面试官兄弟你说你会Webpack那说说他的原理

5次阅读

共计 8821 个字符,预计需要花费 23 分钟才能阅读完成。

前言

大家好,我是林三心,题目 腾讯面试官:同学,你说你会 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/index
import {age} from './aa.js'
import {name} from './hh.js'

console.log(`${name}往年 ${age}岁了 `)

// src/aa.js
export const age = 18

// src/hh.js
console.log('我来了')
export const name = '林三心'

1. 定义 Compiler 类

// index.js
class 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').default

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
  }
}

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').default
const {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').default
const {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').default
const {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 岁了

结语

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

正文完
 0