Coder Social home page Coder Social logo

webpack-mini's Introduction

mini-webpack

📚 实现最简 webpack

读取文件内容createAsset

读取文件内容一共分为两步

读取内容

  • 使用fs.readFileSync读取内容

获取文件的依赖关系

  • 使用@babel-parser解析 AST 树, 获取代码(node.source.value)
  • 使用@babel/traverse遍历 AST 树, 获取代码的依赖, 添加到deps
  • 使用babel-core将 ESM 的代码转换成 CJS 的代码

createAsset返回

{
  filePath, // 文件路径
  code, // 生成的代码
  deps, // 文件的依赖
  mapping: {}, // 用于查找的索引, 初始化为空
  id, // 索引的id
}

生成依赖图createGraph

遍历入口文件的deps, 为所有的dep调用createAsset, 将结果放到一个queue中, 作为graph返回

这里会把文件路径filePath作为mappingkey, idvalue, 给mapping赋值

生成模板build

循环生成的依赖图graph, 获取code, id, mapping, 通过ejs模板, 调用fs.writeFileSync写入bundle.js

require

通过id, 去寻找mapping中的依赖, 并执行

打包完成

最终会打包成一个立即执行函数, 参数为mapping后的所有依赖

// 一个文件的例子
1: [ // id
	function (require, module, exports) {
	const { foo } = require('./foo.js')
		foo()
		console.log('main.js')
	},
	{ './foo.js': 2 }
],

运行

node index.js

打开example中的index.html

成功后在控制台会输出

foo
bar
main.js

webpack-mini's People

Contributors

cuiyiming1998 avatar

Stargazers

young avatar  avatar

Watchers

James Cloos avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.