웹팩 패키지 원리 분석 및 실현 (1)
5041 단어 웹 프런트엔드
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 처리 의존 모듈의 경로
어떻게 스스로 간단한 웹 패키지 포장 절차를 실현합니까?
실현 절차
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에 가입하여 함께 학습하고 교류하는 것을 환영합니다.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
highcharts 데이터 테이블 설정 두 가지 등효 방식의 쓰기텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.