웹팩 패키지 원리 분석 및 실현 (1)

5041 단어 웹 프런트엔드
  • 웹팩 포장 원리 분석 및 실현(一)
  • 웹팩 포장 원리 분석 및 실현(二)
  • 웹팩 포장 원리 분석 및 실현(3)
  • 우선 빈 폴더를 새로 만들고 편집기(webstrom)가 폴더를 열고 npm init-y를 실행하여 패키지를 생성합니다.json, 루트 디렉터리에 웹 패키지를 새로 만듭니다.config.js, 다음 코드 추가(webpack 4.0의 기본 설정)
    const path=require('path');
    module.exports={
        entry:'./src/index.js',
        mode:'development',
        output:{
            path:path.resolve(__dirname,'./dist'),
            filename:'main.js'
        }
    };
    

    새 src 디렉터리, index를 추가합니다.js,exop.js expo.js
    export const add=(a,b)=>{
        return a+b
    }
    export const minus=function (a,b) {
        return a-b
    }
    

    index.js
    import {add,minus} from "./expo.js"
    add(1,2)
    console.log("hello webpack")
    

    npx 웹팩을 실행하면 생성된 파일/dist/main을 볼 수 있습니다.js:
     (function(modules) { // webpackBootstrap
     	// The module cache
     	var installedModules = {};
    
     	// The require function
     	function __webpack_require__(moduleId) {
    
     		// Check if module is in cache
     		if(installedModules[moduleId]) {
     			return installedModules[moduleId].exports;
     		}
     		// Create a new module (and put it into the cache)
     		var module = installedModules[moduleId] = {
     			i: moduleId,
     			l: false,
     			exports: {}
     		};
    
     		// Execute the module function
     		modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
    
     		// Flag the module as loaded
     		module.l = true;
    
     		// Return the exports of the module
     		return module.exports;
     	}
    	...
    
     	// Object.prototype.hasOwnProperty.call
     	__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
    
     	// __webpack_public_path__
     	__webpack_require__.p = "";
    
    
     	// Load entry module and return exports
     	return __webpack_require__(__webpack_require__.s = "./src/index.js");
     })
     ...
    
    

    패키지 후 생성된 코드는 브라우저의 컨트롤러에서 직접 실행할 수 있습니다. 대체적으로 웹 패키지는 웹 패키지를 실현했습니다require는 자신의 모듈화를 실현하고 코드를 모두installed Modules에 캐시한다. 코드 파일은 대상으로 전달되고 키는 경로이다.value는 패키지의 코드 문자열이며 코드 내부의 Require는 웹팩으로 대체된다require 처리 의존 모듈의 경로
    어떻게 스스로 간단한 웹 패키지 포장 절차를 실현합니까?

    실현 절차

  • 기본 설정, 웹 패키지에서 설정을 읽습니다
  • 입구 모듈
  • 찾기
  • 입구 분석
  • 분석 이래 모듈(모듈을 가져오는 경로)
  • 내용 분석(내용 처리)
  • 컴파일 내용
  • 의존 모듈(귀속 의존 찾기)
  • 분석 이래 모듈
  • 분석 의존 모듈(내용 처리)
  • 컴파일 내용
  • bundle 생성.js, 코드는 브라우저에서 직접 실행할 수 있음
  • 스스로 버블을 실현하다.js
  • 모듈 분석: 입구 파일 읽기, 코드 분석 새 파일./lib/webpack.js, 그 중에서 node의 fs를 이용하여 파일 내용을 읽고 파일에 의존하기 위해 문자열로 캡처하는 것을 추천하지 않습니다. 도입된 모듈 이름이 많을수록 번거롭고 원활하지 않습니다. @babel/parser를 추천합니다. 이것은 babel7의 도구입니다. es6의 내부 문법을 분석하고 ast 추상 트리 npm i @babel/parser --save
  • 를 되돌려줍니다.
    const fs = require('fs')//node     fs
    constructor(options) {
            console.log(options)
            const {entry, output} = options
            this.entry = entry
            this.output = output
            //       
            this.modules = []
        }
         run() {//    
            const info = this.parse(this.entry)
            console.log(info)
            }
         parse(entryFile) {
            //!          
            const content = fs.readFileSync(entryFile, 'utf-8')
            console.log(content)
    
            //!        ?       
            const ast = parser.parse(content, {
                sourceType: 'module'
            })
            console.log(ast.program.body)
        }
    

    새 build.js
    //!   webpack     
    const options =require("./webpack.config.js")
    const webpack=require('./lib/webpack')
    //    
    new webpack(options).run()
    

    node build을 실행합니다.js, ast body 섹션 인쇄
    [ Node {
        type: 'ImportDeclaration',
        start: 0,
        end: 35,
        loc: SourceLocation { start: [Position], end: [Position] },
        specifiers: [ [Node], [Node] ],
        source:
         Node {
           type: 'StringLiteral',
           start: 24,
           end: 35,
           loc: [SourceLocation],
           extra: [Object],
           value: './expo.js' },
        trailingComments: [ [Object] ] },
      Node {
        type: 'ExpressionStatement',
        start: 44,
        end: 52,
        loc: SourceLocation { start: [Position], end: [Position] },
        expression:
         Node {
           type: 'CallExpression',
           start: 44,
           end: 52,
           loc: [SourceLocation],
           callee: [Node],
           arguments: [Array] } },
      Node {
        type: 'ExpressionStatement',
        start: 54,
        end: 82,
        loc: SourceLocation { start: [Position], end: [Position] },
        expression:
         Node {
           type: 'CallExpression',
           start: 54,
           end: 82,
           loc: [SourceLocation],
           callee: [Node],
           arguments: [Array] },
        trailingComments: [ [Object] ] } ]
    
    

    보입니다, index.js의 세 줄 코드는 각각 가져오기, 표현식, 표현식으로 해석된다
    import {add,minus} from "./expo.js" //    
    add(1,2)      
    console.log("hello webpack")//      
    

    만약 당신이 프로그래밍을 좋아하거나 어떤 문제에 부딪히면 663077768에 가입하여 함께 학습하고 교류하는 것을 환영합니다.

    좋은 웹페이지 즐겨찾기