利用最近本身寫的一個針對多頁應用而寫的腳手架,對本身第一個寫的項目進行重構。哈哈,那個時候剛入門前端,還不知道有webpack這種東西,寫的是那種最最古老的Bootstrap + jquery項目,那時還不懂什麼是打包... 通過半年來的學習,成長到如今,回頭看看本身第一次的項目,還真是慘不忍睹啊~ 好吧,不囉嗦了,開始吧。javascript
先看看之前這個項目長什麼樣子....css
css ———— | —— introduction.css | —— index.css | —— owl.carousel.min.css js ———— | —— initIntro.js | —— initScroller.js | —— index.js | —— iscroll-probe.js | —— owl.carousel.min.js img ———— ......... index.html introduction.html
一共就只有2個頁面,一個主頁index
和一個詳情介紹頁introduction
。 看着這個目錄結構此刻的心情(/ω\)html
npm install
安裝全部依賴後-npm run create index introduction
建立2個目錄,把舊項目的文件拷到對應文件夾,並按照上述內容,把第三方庫都放在一個lib
文件夾下。並把images
文件夾存放在src/static
下。如今的目錄結構前端
static // 靜態資源的存放 | ———— imgs src | ———— views | | ———— index | | | ———— index.html | | | ———— index.css | | | ———— index.js | | | ———— initScroller.js | | ———— introduction | | ———— index.html | | ———— index.css | | ———— index.js | ———— lib | ———— owl.carousel.min.css | ———— owl.carousel.min.js | ———— iscroll-probe.js
js
、css
的引入<script>
標籤引入腳本,用<link>
引入樣式。同時這個舊項目也有用到bootcss的cdn
。這裏仍是比較推薦使用cdn
的,畢竟能夠減小打包後文件的大小。cdn
引入相信你們都會,就不說了。import
去引入相關的js
和css
文件,腳手架已集成了各類loader。CommonJS
的第三方庫,要麼你去改造它,要麼只好直接用<script>
引入吧(儘管很不肯意)cdn
咱們經過npm
安裝JQuery
和Bootstrap
,可是v3
版本不支持模塊化,那麼咱們趁此機會入坑v4-beta
吧JQuery
和Bootstrap v4
npm install jquery npm install popper.js npm install bootstrap@4.0.0-beta
官方文檔中有用到webpack.ProvidePlugin,使用它就能夠自動加載模塊,不須要手動的在每一個js
文件前import
或require
引入
並且還須要用到export-loader(ε=(´ο`*)))唉 好麻煩吶),官方文檔要求,若是咱們要按需引入組件的時候就須要藉助export-loader
去幫咱們在組件的js代碼中去添加module.exports = ...
這樣才能實現按需引入。jquery
npm install export-loader -D
而後在咱們的webpack.dev.conf.js
和webpack.prod.conf.js
中的Plugin:[]
中添加下面的代碼webpack
new webpack.ProvidePlugin({ $: 'jquery', jQuery: 'jquery', 'window.jQuery': 'jquery', Popper: ['popper.js', 'default'], // In case you imported plugins individually, you must also require them here: Util: "exports-loader?Util!bootstrap/js/dist/util", Dropdown: "exports-loader?Dropdown!bootstrap/js/dist/dropdown", })
這裏就會發現dev
和prod
有重複的部分了。而且咱們之後每引入一個組件就必須在這裏添加相似的一行代碼Dropdown: "exports-loader?Dropdown!bootstrap/js/dist/dropdown"
,因此就頗有必要去寫一些函數去處理這些狀況。git
首先在build
中建立bootstrap-components.js
文件,主要用於批量生成bootstrap組件的配置。
注意: 以後添加組件的時候只須要在這裏添加便可!!github
let components = [ 'Util', 'Dropdown', ]; module.exports = (function (){ let o = {}; for(let name of components) { o[name] = `exports-loader?${name}!bootstrap/js/dist/${name.toLowerCase()}` } return o; })();
以後在utils.js
中增長這些代碼,用於生成providerPlugin
的配置。web
var webpack = require('webpack') var components = require('./bootstrap-components') exports.genProviderPlugin = function () { return new webpack.ProvidePlugin(Object.assign({ $: 'jquery', jQuery: 'jquery', 'window.jQuery': 'jquery', Popper: ['popper.js', 'default'], }, components)); }
最後只須要分別在webpack.dev.conf.js
和webpack.prod.conf.js
中的plugins: []
中添加utils.genProviderPlugin()
便可。
至此,便完成了bootstrap-v4.0
的配置,可是v4和v3之間存在很大的差異,有許多的樣式須要去更改~
這篇文章主要是以本身的第一個爛項目做爲例子,經過項目目錄結構, 頁面模塊化,更新框架這三個方面進行了一波重構,讓老舊項目也能夠享受現代Web的開發模式。