Webpack如何引入bootstrap的方法,webpackbootstrap
Bootstrap中是一種事實上的介面標準,標準到現在的網站大量的使用它。如果可以使用webpack引入的bootstrapcss,就可以一個npm install完成項目的依賴,而不必手工的添加到html內。
本來以為在入口檔案內加一行就行:
import 'bootstrap/dist/css/bootstrapcss'
然後安裝依賴:
npm i bootstrap url url-loader style-loader css-loader --save
實際上卻不是想象的那麼簡單。因為css檔案內還引用了很多類型的字型檔和向量圖檔案。要引入它,必須同時提供css之外的類型的對應的loader:
//webpackconfigjs:moduleexports = {entry: {'js'},output: {filename: 'bundlejs'},module: {loaders: [{ test: /\css$/, loader: 'style-loader!css-loader' },{ test: /\eot(\?v=\d+\\d+\\d+)?$/, loader: "file" },{ test: /\(woff|woff2)$/, loader:"url?prefix=font/&limit=5000" },{ test: /\ttf(\?v=\d+\\d+\\d+)?$/, loader: "url?limit=10000&mimetype=application/octet-stream" },{ test: /\svg(\?v=\d+\\d+\\d+)?$/, loader: "url?limit=10000&mimetype=image/svg+xml" }]}};
我們在html檔案內使用那麼一點點的bootstrap:
// chtml<html><body><ul class="nav nav-pills"><li role="presentation" class="active"><a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" >Home</a></li><li role="presentation"><a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" >Profile</a></li><li role="presentation"><a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" >Messages</a></li></ul><script type="text/javascript" src="bundlejs"></script></body></html>
再次執行轉譯:
webpack
開啟瀏覽器:
open chtml
看到bootstrap那熟悉而太熟悉的介面。
引入jquery
如果需要使用bootstrap的js外掛程式的話,就必須首先引入jquery。引用jquery的一個方法是使用webpack外掛程式。
首先安裝jquery:
npm i jquery
其次使用外掛程式裝入jquery,方法是修改webpack的設定檔,加入:
plugins: [new webpackProvidePlugin({$: "jquery",jQuery: "jquery"})]
在入口檔案內加入代碼來做驗證:
$("body")append("<div>hello world</div>")
如果成功,說明jquery載入成功。這樣你就可以在入口js檔案內載入bootstrapjs了:
import 'bootstrap/dist/js/bootstrapjs'
排除錯誤
我確實在引入bootstrap的時候,遇到一個神奇的錯誤。在webpack轉譯時報錯,css-loader,unknown word樣子的錯誤。對webpackconfigjs檔案加入一個include屬性並指向到不存在的目錄即可。
{test: /\css$/,include: [pathresolve(__dirname, "not_exist_path")],loader: "style!css"}
原始的issue在此:https://githubcom/webpack/cs 。我看看看到此答案時以為是個玩笑。
以上就是本文的全部內容,希望對大家的學習有所協助,也希望大家多多支援幫客之家。