웹 팩 학습 노트 - 캐 시 최적화

이 글 을 보기 전에 브 라 우 저 캐 시 원리 에 대해 잘 모 르 면 브 라 우 저 캐 시 라 는 기본 지식 을 복습 합 니 다.파일 요약 알고리즘 에 대해 잘 모 르 면 파일 요약 알고리즘 이라는 기초 지식 을 먼저 복습 합 니 다.
vue - cli 로 만 든 프로젝트 는 포장 할 때 nodemodules 디 렉 터 리 에서 모든 파일 을 분리 하여 vendor. js 를 단독으로 생 성 합 니 다.
// split vendor js into its own file
new webpack.optimize.CommonsChunkPlugin({
    name: "vendor",
    minChunks: function (module, count) {
        // any required modules inside node_modules are extracted to vendor
        return (
            module.resource &&
            /\.js$/.test(module.resource) &&
            module.resource.indexOf(
                path.join(__dirname, "../../node_modules")
            ) === 0
        );
    }
}),

node_modules 의 외부 플러그 인 업데이트 가 빈번 하지 않 기 때문에 브 라 우 저 캐 시 를 이용 하여 페이지 성능 을 향상 시 킬 수 있 는 파일 을 따로 만 드 는 것 은 좋 은 실천 입 니 다.
실제 작업 에서 기 존 구성 요소 의 코드 만 수정 하면 포 장 된 vendor. js 의 hash 코드 는 변 하지 않 습 니 다.But!구성 요 소 를 새로 쓰 고 프로젝트 를 도입 하면 압축 된 모든 파일 의 hash 코드 가 모두 변 경 됩 니 다. vendor. js 를 포함 합 니 다.
레 퍼 런 스https://webpack.js.org/guides...이후 웹 팩 캐 시 최적화 문 제 를 대충 알 아 냈 다.
현재 프로젝트 가 세 개의 구성 요소 라 고 가정 하면 jquery 까지 만 사용 합 니 다.일반적인 상황 에서 모든 구성 요 소 는 웹 팩 을 포장 한 후에 배열 항목 으로 저 장 됩 니 다.
// main.js       ,    id 1,2,3
webpackJsonp([0],[
    /* 0 */,
    /* 1 */
    (function(module, __webpack_exports__, __webpack_require__){...}),
    /* 2 */
    (function(module, __webpack_exports__, __webpack_require__){...}),
    /* 3 */
    (function(module, __webpack_exports__, __webpack_require__){...})
],[1]);

//jquery.js     vendor.js       
webpackJsonp([1],[
    /* 0 */
    (function(module, exports, __webpack_require__) {...}),
    /* 1 */,
    /* 2 */,
    /* 3 */,
    /* 4 */
    (function(module, exports, __webpack_require__) {
        module.exports = __webpack_require__(0);    
    })
],[4]);

그래서 웹 팩 내부 에서 구성 요소 의 호출 은 배열 의 index 에 의 해 이 루어 집 니 다. 프로젝트 의 모든 구성 요 소 는 하나의 유일한 index 를 가지 고 있 습 니 다.내 가 구성 요 소 를 새로 추가 할 때 main. js 의 배열 은 확장 되 고 vendor. js 의 배열 도 다시 배열 되 기 때문에 앞에서 말 한 문 제 를 야기 합 니 다.
//      ,main.js       ,    id 1,2,3,4
webpackJsonp([0],[
    /* 0 */,
    /* 1 */
    (function(module, __webpack_exports__, __webpack_require__){...}),
    /* 2 */
    (function(module, __webpack_exports__, __webpack_require__){...}),
    /* 3 */
    (function(module, __webpack_exports__, __webpack_require__){...}),
    /* 4 */
    (function(module, __webpack_exports__, __webpack_require__){...})
],[1]);

//jquery.js     vendor.js    
webpackJsonp([1],[
    /* 0 */
    (function(module, exports, __webpack_require__) {...}),
    /* 1 */,
    /* 2 */,
    /* 3 */,
    /* 4 */,
    /* 5 */
    (function(module, exports, __webpack_require__) {
        module.exports = __webpack_require__(0);    
    })
],[5]);

이 문 제 를 해결 하 는 방법 홈 페이지 에서 추천 하 는 것 은 new webpack. Hashed ModuleIdsPlugin () 이라는 플러그 인 입 니 다. 이 플러그 인 을 도입 하면 문 제 는 존재 하지 않 습 니 다.호기심 이 나 로 하여 금 이 플러그 인 이 도대체 무엇 을 했 는 지, 어떻게 하면 vendor. js 가 외부 가방 의 영향 을 받 지 않도록 할 수 있 습 니까?
코드 가 매우 짧 고 간결 한 것 을 발견 하 다.
const createHash = require("crypto").createHash;

class HashedModuleIdsPlugin {
    constructor(options) {
        this.options = Object.assign({
            hashFunction: "md5",
            hashDigest: "base64",
            hashDigestLength: 4
        }, options);
    }

    apply(compiler) {
        const options = this.options;
        compiler.plugin("compilation", (compilation) => {
            const usedIds = new Set();
            compilation.plugin("before-module-ids", (modules) => {
                modules.forEach((module) => {
                    if(module.id === null && module.libIdent) {
                        const id = module.libIdent({
                            context: this.options.context || compiler.options.context
                        });
                        //         ,  md5
                        const hash = createHash(options.hashFunction);
                        //    id      
                        hash.update(id);
                        //    base64  
                        const hashId = hash.digest(options.hashDigest);
                        let len = options.hashDigestLength;
                        //          base64 4   ,           ,        ,        ,             。
                        while(usedIds.has(hashId.substr(0, len)))
                            len++;
                        //            module.id
                        module.id = hashId.substr(0, len);
                        //  module.id   usedIds   ,                
                        usedIds.add(module.id);
                    }
                });
            });
        });
    }
}

module.exports = HashedModuleIdsPlugin;

그래서 이렇게 간단 한 방식 으로 원래 의 데이터 구 조 를 대상 구조 로 바 꾸 었 다.HashedModuleIdsPlugin 플러그 인 으로 포 장 된 vendor. js 코드 가 이렇게 되 었 습 니 다.
//jquery.js     vendor.js    
webpackJsonp([1],{
    /***/ 0:
    /***/ (function(module, exports, __webpack_require__){...}),
    
    /***/ "tra3":
    /***/ (function(module, exports, __webpack_require__) {...})
},[0]);

이렇게 하면 배열 로 인 한 번호 재 배열 문제 에서 벗 어 나 jquery 내부 코드 가 변 하지 않 으 면 이 vendor. js 의 hash 는 변 하지 않 을 것 을 보증 합 니 다.

좋은 웹페이지 즐겨찾기