Webpack4系列教程(七) 单页面解决方案

写在前面

本节课讲解webpack4打包单页应用过程中的代码分割和代码懒加载。不同于多页面应用的提取公共代码,单页面的代码分割和懒加载不是通过webpack配置来实现的,而是通过webpack的写法和内置函数实现的。

优势

通过代码分割和代码懒加载,我们可以让用户在更短的时间内去看到他想要的页面

目前webpack针对此项功能提供 2 种函数:

import

目录结构
在这里插入图片描述

配置文件

module.exports = {
    entry: {
        app: './src/index.js'
    },
    output: {
        filename: '[name].bundle.js',
        chunkFilename: '[name].chunk.js',
        path: path.resolve('dist')
    },
    mode: 'development',
    plugins: [
        new CleanPlugin('dist'),
        new HtmlPlugin({
            template: './src/index.html',
            hash: true
        })
    ]
}

index.js入口文件代码

import(/* webpackChunkName: 'a'*/"./js/a").then(function(a){
    console.log('我是入口文件,我引用了子文件:' + a);
});
import(/* webpackChunkName: 'b'*/"./js/b").then(function(b){
    console.log('我是入口文件,我引用了子文件:' + b);
});

执行打包命令
在这里插入图片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章