本文主要講了webpack怎麼搭建多頁應用,熟悉下webpack的基本用法。html
新建文件夾,目錄結構以下:webpack
而後web
根目錄下新建webpack.config.js開始配置,參照這裏npm
js部分的處理:json
演示:在src > page > index下新建index.js隨便輸入一行代碼,好比console.log('index')
,修改webpack.config.js測試
在命令行輸入webpack,能夠看到根目錄下多了個dist文件夾,src/page/index/index.js被打包到了dist/index.js裏面,下面咱們修改哈配置文件,讓他能夠打包多入口的狀況ui
這樣咱們已經能夠分別打包了,可是若是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:
說明打包成功,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>
再次打包,可看到:
到此,公共html也生效了,還剩下樣式的處理和單獨打包,下次繼續第一次寫,有些凌亂