Webpack打包多html文件spa,Webpack打包多页面应用

正常情况下项目都是打包成一个index.html主文件入口就ok了,这个是针对单页面SPA,但像传统项目那种多页面维护的架构,也是可以用webapack来打包的

项目目录结构如图所示:

bVbGzou

需要完成的效果如图所示:

bVbGzoC

template里面的index.html

Document 首页 产品 关于

在webpack配置文件之前,先介绍一个可以实现多文件打包的插件html-webpack-plugin以及介绍该插件的参数设置

title:生成html文档的标题。

filename:输出文件的文件名称,默认为index.html,还可以指定输出文件目录(html/index.html)。

template:本地模板文件的路径,支持加载器(如handlebars、ejs、undersore、html等)。

inject:true | 'head' | 'body' | false,注入所有资源到特定的template或templateContent中,如果设置为true或body,则所有的Javascript资源将被放置到body元素的底部,设置为head将放置到head元素中,设置为false表示所有的静态资源都不会被放置到模板中。

favicon:添加特定的 favicon 路径到输出的 HTML 文件中。

hash:true | false 表示是否给所有包含的js、css文件后面添加hash值,可以用来清除缓存,

chunks:用来指定生成的html文件需要包括哪些入口文件,如不设置则所以入口JS文件都会被引入进来。

如:入口文件有index.js\main.js\common.js,如果chunks不设置,则这几个入口文件都会被引入,如设置chunks:['index','main']则index.js\main.js文件会被引入。

配置项目太多,并不是所有的都用到这个只是一个介绍

webpack.config.js

const path = require('path');

const HtmlWebpackPlugin = require('html-webpack-plugin');

const { CleanWebpackPlugin } = require('clean-webpack-plugin');

module.exports = {

//配置多入口,既然打包多页面那也要配置多入口

entry: {

home: './src/home/index.js',

product: './src/product/index.js',

about: './src/about/index.js'

},

//出口路径配置

output: {

filename: 'js/[name].[contentHash].js', //这个主要作用是将打包后的js已hash值的编码方式来生成出来

path: path.resolve(__dirname, './dist')

},

mode: 'production',

plugins: [

//在每一次编译前都清除output输出的路径 CleanWebpackPlugin的主要作用

new CleanWebpackPlugin(),

//HtmlWebpackPlugin配置

new HtmlWebpackPlugin({

title: '首页',

template: './template/index.html',

filename: 'home.html',

chunks: ['home']

}),

new HtmlWebpackPlugin({

title: '产品',

template: './template/index.html',

filename: 'product.html',

chunks: ['product']

}),

new HtmlWebpackPlugin({

title: '关于我们',

template: './template/index.html',

filename: 'about.html',

chunks: ['about']

})

]

}

cmd控制台执行指令:webapck,然后dist目录下会生成多个页面如图

bVbGzqz

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值