31 webpack中的多页应用

多页应用

之前我们的学习都是在单页面(Spa)程序的基础上进行的,在此章节,我们将介绍如何在Webpack中进行多页面应用(Mpa)的构建。

配置代码如下:

const HtmlwebpackPlugin = require('html-webpack-plugin');
const path = require("path");

module.exports = {
    
    
    entry: {
    
    
        index: './src/index/index.js',
        about: './src/about/index.js',
        news: './src/news/index.js'
    },
    output: {
    
    
        filename: '[name].js',
        path: path.resolve(__dirname, 'dist')
    },
    plugins: [
        new HtmlwebpackPlugin({
    
    
            // 模板文件
            template: './src/index/index.html',
            // 输出文件名称
            filename: path.resolve(__dirname, 'dist/index/index.html'),
            // 引入的chunk,在这里表示只引入生成的index.js
            // 默认的会引入 index about news三个js文件
            // chunks规定文件引入那些chunk
            chunks: ['index']
        }),
        new HtmlwebpackPlugin({
    
    
            template: './src/about/index.html',
            filename: path.resolve(__dirname, 'dist/about/index.html'),
            chunks: ['about']
        }),
        new HtmlwebpackPlugin({
    
    
            template: './src/news/index.html',
            filename: path.resolve(__dirname, 'dist/news/index.html'),
            chunks: ['news']
        }),
    ],
    devServer: {
    
    
        // 默认展示index/index.html
        contentBase: path.resolve(__dirname, 'dist/index')
    }
}

在这里我们多次使用HtmlwebpackPlugin插件来实现多页面的构建。对于多页面的构建,会产生很多重复的操作,你可以合理的组织项目的页面结构,然后封装一个工具函数,把重复的代码抽离出来,减少重复劳动。在这里还可以使用Web-webpack-plugin插件来实现多页面应用,同样该插件规定你的项目页面结构也是有规律性的。

本章节提供案例源码下载:https://gitee.com/mvc_ydb/webpack/blob/master/mpa.zip

猜你喜欢

转载自blog.csdn.net/sinat_41212418/article/details/121941059
31
31)
今日推荐