2.1 webpack 之 模块拆分打包配置 附源码

676 阅读2分钟

    在前面几节,基本已经介绍完了webpack的基本用法,可以去总目录阅读对应的章节。但是有个问题我们打包的js文件都是只有一个index.js,当项目庞大的时候,这个js异常大,首次加载的时候非常耗时!
    好了有了需求我们就得去找解决方法!

一、wepack 打包多js文件

这里我们就给自己构建一个需求!
入参:两个html(index.html,other.html),两个js(home.js,other.js),两个css(index.css,other.css)
出参:index.js拆分输出,并且index.html引用home.js,other.html引用other.js。

  • 1.先创建这几个文件吧

index.html 中多加了一个跳转代码<a href="./other.html">go other html</a>
index.js 代码

require('./index.css')
console.log('hello home')

other.js 代码

require('./other.css')
console.log('hello other')

index.css 代码

body{
    background: rebeccapurple;
}

other.css 代码

body{
    background: aqua;
}

此时我们直接执行npm run build (这里说明下每个小节都是基于上个小节讲解的)。可以完成编译,但是还是输出了一个js!
有的朋友会说,你都没有告诉webpack怎么输出,当然还是原来的!所以我们还需要配置下项目的webpack.config.custom.js文件

  • 1.配置多入口
   entry: {
        home:'./src/index.js',
        other:'./src/other.js'
    }, //入口
  • 2.配置多输出
 output: {
        filename: '[name].js', // [name] 指的是多个入口,这里指 home other
        path: path.resolve(__dirname,'dist'),  // 路径必须是一个绝对路径
    },
  • 3.html 插件指定引用js配置
new HtmlWebpackPlugin({
            template: "./src/index.html",
            filename: "index.html",
            minify: {
                 removeAttributeQuotes:false, // 删除引号
                 collapseWhitespace:false, // 去除空格
                // hash:true
            },
            chunks: ['home'] // 指定引用home
        }),
new HtmlWebpackPlugin({
            template: "./src/other.html",
            filename: "other.html",
            minify: {
                removeAttributeQuotes:false, // 删除引号
                collapseWhitespace:false, // 去除空格
                // hash:true
            },
            chunks: ['other'] // 指定引用 other,两个都要就这么写['other','home']
        }),
  • 4.css 配置多输出
new MiniCssExtractPlugin({
            filename:'[name].css', //[name] 指的是多个入口,会输出js同名的css
            chunkFilename:'[id].css'
        }),

现在我们在执行npm run build

看上去已经ok了,我们在去浏览器加载下index.html,瞅瞅效果哈!

在点击 go other html

源码下载

创建文件夹,cd至已创建文件夹,执行 git clone https://gitee.com/dolan_ge/webpack.git -b webpack_multi_module

进入webpack工程目录,执行 npm install -D