code split

Reads: 2045 Edit

比如将一个大文件分割成三个文件,这样加载时更快。

第一种配置方式

index.js

import {sub} from "./test"

console.log("--- load css ---");

console.log(sub(5,2));

test.js

export function add2(x,y){
    return x + y;
}

export function sub(x,y){
    return x - y;
}

webpack.config.js

//引用Node.js中的path模块,处理文件路径的小工具
const path = require("path");
//引入插件
const HtmlwebpackPlugin = require("html-webpack-plugin")

// 导出一个webpack具有特殊属性配置的对象
module.exports = {
    mode: "development" ,
    //入口
     //入口模块文件路径
    entry:  "./src/js/index.js"  ,
    //出口是对象
    output: {
        //path是一个绝对路径,__dirname 是当前js的绝对路径
        path: path.join(__dirname , "./dist/"), //打包的结果文件存储目录
        filename : "bundle[hash:10].js"  //打包的结果文件名
    },module:{ //模块
          rules: [  // 规则
          
          ]
    },
    //配置插件
    plugins: [
        new HtmlwebpackPlugin({
            //此插件作用是将 index.html打包到bundle.js所在目录中
            //同时会在 index.html中自动的在<script>引入 bundle.js
            template : "./src/index.html"
        })
    ] ,
    // 实时重新加载
    devServer: {
        contentBase: "./dist" ,
        compress: true,
        port: 8888,
        open: true
    } 
}

然后运行 npm run build ,会发现dist目录下只有一个js文件,把index.js和test.js的内容都放在这个js文件里了

333708

2 根据入口文件进行分割

修改 index.js

console.log("--- load css ---");

修改 webpack.config.js

//引用Node.js中的path模块,处理文件路径的小工具
const path = require("path");
//引入插件
const HtmlwebpackPlugin = require("html-webpack-plugin")

// 导出一个webpack具有特殊属性配置的对象
module.exports = {
    mode: "development" ,
    //多入口
    entry:  {
        main :"./src/js/index.js" ,
        test : "./src/js/test.js"
    }  ,
    //出口是对象
    output: {
        //path是一个绝对路径,__dirname 是当前js的绝对路径
        path: path.join(__dirname , "./dist/"), //打包的结果文件存储目录
        filename : "[name].[hash:10].js"  //打包的结果文件名
    },module:{ //模块
          rules: [  // 规则
          
          ]
    },
    //配置插件
    plugins: [
        new HtmlwebpackPlugin({
            //此插件作用是将 index.html打包到bundle.js所在目录中
            //同时会在 index.html中自动的在<script>引入 bundle.js
            template : "./src/index.html"
        })
    ] ,
    // 实时重新加载
    devServer: {
        contentBase: "./dist" ,
        compress: true,
        port: 8888,
        open: true
    } 
}

然后运行 npm run build后悔发现,dist目录下有两个js文件

QQ截图20200228214118

第二种配置方式

第一种配置方式的缺点是很难指定多个入口,不太灵活

测试引入jquery模块

npm install jquery -D

index.js

import $ from "jquery"

console.log("--- load css ---");

$(document).ready(function(){
    $("#test1").text("Hello world!");
});

console.log($)

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>    
    <div id="box1"></div>
    <div id="box2"></div>
     
    <p id="test1"></p>

</body>
</html>

webpack.config.js

//引用Node.js中的path模块,处理文件路径的小工具
const path = require("path");
//引入插件
const HtmlwebpackPlugin = require("html-webpack-plugin")

// 导出一个webpack具有特殊属性配置的对象
module.exports = {
    mode: "development" ,
    //多入口
    entry: "./src/js/index.js" ,
    //出口是对象
    output: {
        //path是一个绝对路径,__dirname 是当前js的绝对路径
        path: path.join(__dirname , "./dist/"), //打包的结果文件存储目录
        filename : "[name].[hash:10].js"  //打包的结果文件名
    },module:{ //模块
          rules: [  // 规则
          
          ]
    },
    //配置插件
    plugins: [
        new HtmlwebpackPlugin({
            //此插件作用是将 index.html打包到bundle.js所在目录中
            //同时会在 index.html中自动的在<script>引入 bundle.js
            template : "./src/index.html"
        })
    ] 
    // 可以将node_modeles中代码单独打包成一个chunk最终输出
    // , optimization: {
    //     splitChunks: {
    //         chunks: "all"
    //     }
    // }
}

运行npm run build,会发现有一个main*.js,比较大

109

打开 optimization选项,在运行 npm run build,会发现有2个js文件

32

第三种方式

通过js代码,让某个文件被单独打包成一个文件

index.js

//import $ from "jquery"
//console.log($)

console.log("--- load css ---");

// $(document).ready(function(){
//     $("#test1").text("Hello world!");
// });



import ("./test")
   .then( (result) => {
        console.log(result);
    })
   .catch( () => {
        console.log("文件加载失败");
    });

运行 npm run build ,查看 index.html结果

QQ截图20200228221829

修改 index.js

//import $ from "jquery"
//console.log($)

console.log("--- load css ---");

// $(document).ready(function(){
//     $("#test1").text("Hello world!");
// });

import ("./test")
   .then( ( {add2,sub} ) => {
        console.log(add2(2,3));
        console.log(sub(10,3));
    })
   .catch( () => {
        console.log("文件加载失败");
    });

然后运行 npm run build,查看构建后的index.html ,查看输出结果。

编译后发现 test.js打包后的id.js没有,需要给打包的tets.js起个名字

修改 webpack.config.js

//import $ from "jquery"
//console.log($)

console.log("--- load css ---");

// $(document).ready(function(){
//     $("#test1").text("Hello world!");
// });

//希望id是固定的
import (/* webpackChunkName:'test' */ "./test")
   .then( ( {add2,sub} ) => {
        console.log(add2(2,3));
        console.log(sub(10,3));
    })
   .catch( () => {
        console.log("文件加载失败");
    });

再次运行 npm run build

122707

关于作者

王硕,网名信平,十多年软件开发经验,业余架构师,精通Java/Python/Go等,喜欢研究技术,著有《PyQt 5 快速开发与实战》《Python 3.* 全栈开发》,多个业余开源项目托管在GitHub上,欢迎微博交流。


Comments

Make a comment

www.ultrapower.com ,王硕的博客,专注于研究互联网产品和技术,提供中文精品教程。 本网站与其它任何公司及/或商标无任何形式关联或合作。