webpack原理实战笔记

2023-10-19 14:49:42 浏览数 (3)

代码语言:javascript复制
我是歌谣 想加入前端技术群私信我 最近开始webpack原理的书写

代码语言:javascript复制
目录结构
代码语言:javascript复制
核心依赖
代码语言:javascript复制
{
  "name": "mywebpack",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo "Error: no test specified" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@babel/core": "^7.22.10",
    "@babel/parser": "^7.22.7",
    "@babel/preset-env": "^7.22.10",
    "@babel/traverse": "^7.22.8"
  }
}
代码语言:javascript复制
核心代码complier.js
代码语言:javascript复制
const {getAst,getCode,getDependcies}=require("./parser")
module.exports=class Complier{
    constructor(options){
        console.log(options,"options")
       this.entry=options.entry;
       this.output=options.output;
       this.modules=[]
    }
    run(){
       const info= this.build(this.entry)
        this.modules.push(info)
        for(let i=0;i<this.modules.length;i  ){
            const item=this.modules[i];
            const {denpendcies}=item
            if(denpendcies){
                for(let j in denpendcies){
                    this.modules.push(this.build(denpendcies[j]))
                }
            }       
         }
         //转换数据结构
         const obj={}
         this.modules.forEach(item=>{
            obj[item.fileName]={
                denpendcies:item.denpendcies,
                code:item.code
            };
         })
         console.log("obj is",obj)
    }
    build(entryFile){
         let ast=getAst(entryFile)
         let denpendcies=getDependcies(ast,entryFile)
         let code=getCode(ast)
         return {
            entryFile,
            denpendcies,
            code
         }
    }
}
代码语言:javascript复制
parser.js
代码语言:javascript复制
const fs=require("fs")
const parser=require("@babel/parser")

const path = require("path")
const traverse=require("@babel/traverse").default
const {transformFromAst}=require("@babel/core")
module.exports={
    //分析模块 获取AST
    getAst:(fileName)=>{
        let content=fs.readFileSync(fileName,"utf-8")
         return parser.parse(content,{
           sourceType:"module"
        })
    },
    //获取依赖
    getDependcies:(ast,fullName)=>{
        const dependcies=[]
        traverse(ast,{
           ImportDeclaration({node}){
              // denpendcies.push(node.source.value)
              const dirname=path.dirname(fullName)
              console.log(dirname,"dirname is")
              const newPath=path.join(dirname,node.source.value)
              console.log(newPath,"newPath is")
              dependcies[node.source.value]=newPath
           }
        })
        return dependcies
    },
    getCode:ast=>{
        const code=transformFromAst(ast,null,{
            presets:["@babel/preset-env"]
         })
         console.log(code,"code is")
         return code
    }
}
代码语言:javascript复制
运行结果
代码语言:javascript复制
代码地址 https://github.com/geyaoisnice/hand-webpack

0 人点赞