您好,欢迎访问一九零五行业门户网

使用webpack构建多页应用的代码示例

本篇文章给大家带来的内容是关于使用webpack构建多页应用的代码示例,有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。
背景:随着react, vue, angular 三大前端框架在前端领域地位的稳固,spa应用正在被应用到越来越多的项目之中。然而在某些特殊的应用场景之中,则需要使用到传统的多页应用。在使用webpack进行项目工程化构建时,也需要对应到调整。
与spa应用区别
在spa应用中,使用 webpack 构建完成项目之后,会生成一个 html 文件,若干个 js 文件,以及若干个 css 文件。在 html 文件中,会引用所有的 js 和 css 文件。\
而在多页应用中,使用 webpack 构建完成项目之后,会生成多个 html 文件,多个 js 文件,以及多个 css 文件。在每个 html 文件中,只会引用该页面所对应的 js 和 css 文件。
webpack配置
入口设置
多页应用的打包会对应多个入口 js 文件,以及多个 html 模版文件。假设我们的开发状态下的多页目录是这样:
    |--page1        |--index.html        |--index.js        |--index.less    |--page2        |--index.html        |--index.js        |--index.less
包括 page1 和 page2 两个页面,以及它们所对应的 js 和 less 文件。那么在使用 webpack 构建项目时,就有 page1->index.js 和 page2->index.js 两个入口文件,以及 page1->index.html 和 page2->index.html 两个模版文件。然而在构建项目时,不可能针对每一个页面指定一个入口配置。\
要自动匹配到所有的页面入口及模版文件,有两种方法。\
\
方法一:使用 node 的 fs 文件系统。来读取父级文件夹下的所有子文件夹。通过文件夹名称,来自动匹配到所有的页面。然而,这种方式需要保持父级文件夹下文件的干净。否则就需要使用具体的判断逻辑来过滤出所有的入口目录。\
\
方法二:通过配置文件来配置入口。比如:
    entry: ['page1', 'page2'];
这样便能准确的指定出所有的入口目录。然而却在每次增加页面时,都需要去更改配置文件。\
两种方法个有特点,可根据具体情况选择。
具体配置entryentry的配置需要根据我们获取到的入口数据来循环添加。
    const entrydata = {};    entry.foreach(function (item) {        entrydata[item] = path.join(__dirname, `../src/pages/${item}/index.js`);    })
outputoutput的配置和spa应用一致,不需要特殊配置。
    output: {        filename: 'public/[name]_[chunkhash:8].js',        path: path.join(__dirname, `../dist/`),        publicpath: '/'    },
htmlwebpackplugin在使用 webpack 构建时。需要使用到 html-webpack-plugin 插件来生成项目模版。对于需要生成多个模版的多页应用来说,也需要生成多个 html 模版文件。同样的,使用获取到的入口文件数据来循环添加。
    const htmlwebpackplugin = require('html-webpack-plugin');    const htmlwebpackplugindata = [];    entry.foreach(function (item) {        htmlwebpackplugindata.push(            new htmlwebpackplugin({                filename: `${item}.html`,                template: path.join(__dirname, `../src/pages/${item}/index.html`),                chunks: [item]            })        );    })
配置中 chunks 必须配置,如果不配置,会导致每个模版文件中均引入所有的 js 和 css 文件。指定为 entry 中的配置 name,则会只引入该入口相关的文件。
配置组合接下来,便是将前面的entry, output, htmlwebpackplugin的配置组合起来,除此之外的其它配置,跟spa应用一致,无需做单独处理。组合如下
    modules.exports = {        entry: { ...entrydata },        output: {            filename: 'public/[name]_[chunkhash:8].js',            path: path.join(__dirname, `../dist/`),            publicpath: '/'        },        plugins: [            ...htmlwebpackplugindata        ]        ...    }
完整demo可查看多页应用demo
以上就是使用webpack构建多页应用的代码示例的详细内容。
其它类似信息

推荐信息