webpack多页应用

本文主要讲了webpack怎么搭建多页应用,熟悉下webpack的基本用法。html

新建文件夹,目录结构以下:webpack

clipboard.png

而后web

  • cd webpack-test
  • npm init(根目录下建立了一个pakage.json)
  • npm install webpack@1.15.0 --save-dev(安装webpack,我这里用的是1版本)

根目录下新建webpack.config.js开始配置,参照这里npm

js部分的处理:json

演示:在src > page > index下新建index.js随便输入一行代码,好比console.log('index'),修改webpack.config.js测试

clipboard.png

在命令行输入webpack,能够看到根目录下多了个dist文件夹,src/page/index/index.js被打包到了dist/index.js里面,下面咱们修改哈配置文件,让他能够打包多入口的状况ui

clipboard.png

这样咱们已经能够分别打包了,可是若是index > index.js 和 login > index.js同时引用了一个公共js,咱们也但愿能够把公共的东西提取出来单独打包,这就要用到webpack的插件CommonsChunkPlugin,参考这里,注意:webpack4中已经没有这个插件spa

如今让index > index.js 和 login > index.js 同时 require('./../common.js'),修改配置文件:
config里面添加代码:插件

plugins: [
    new webpack.optimize.CommonsChunkPlugin({
        name: 'common', // 对应入口处的common,会总体打包入common
        filename: 'js/base.js'
        // chunks: ['common']
    })
  ]

这里用了new webpack.optimize.CommonsChunkPlugin,因此须要在前面var webpack = require('webpack')命令行

index > index.js:

require('./../common.js')
console.log('index')

login > index.js:

require('./../common.js')
console.log('login')

再次打包,能够看到common.js被单独打包到了base.js

html部分的处理:html-webpack-plugin

上面已经能够打包js了,若是如今咱们要测试打包的内容,须要在page > view 下新建index.html,引入dist/js下面的js,咱们想把html也打包到dist,按需引入本身的js,参考这里

这里要用到插件,须要安装:npm i --save-dev html-webpack-plugin
参见文档修改配置:

new HtmlWebpackPlugin({
   // 打包后的目标文件
   filename: 'view/index.html',
   // 要打包的目标文件
   template: 'src/view/index.html',
   inject: true,
   hash: true,
   // 表示当前html引入公共js和与当前对应的js
   // 须要引入哪些js
   chunks: ['common', 'index']
})

执行webpack,能够看到打包成功,点开dist/view/index.html:

clipboard.png

说明打包成功,base.js和index.js都正确引入
面对多页应用,咱们还常常面临多个页面头部和底部相同的状况,每一个页面去写未免有点麻烦,咱们能够用html-loader解决这个问题
安装:npm install html-loader --save-dev

view下新建layout文件夹,再分别新建header.html和footer.html
heder.html:

<meta charset="utf-8">
<title></title>

footer.html:

<div>我是footer</div>

而后在index.html里面修改:

<!DOCTYPE html>
<html>
<head>
    <%= require('html-loader!./layout/head.html')  %>
</head>
<body>
index
<%= require('html-loader!./layout/footer.html')  %>
</body>
</html>

再次打包,可看到:

clipboard.png

到此,公共html也生效了,还剩下样式的处理和单独打包,下次继续第一次写,有些凌乱

相关文章
相关标签/搜索