css加載器
在webpack中,所有的資源(js文件、css文件、模板文件,圖片文件等等)都被看成是一個模塊,因此多有的資源都是可以被加載的。
加載這些資源我們要在module屬性定義這些加載配置(指定加載器)。
在module屬性中,通過定義loaders定義加載器,其屬性值是一個數組,每一個成員代表一個配置。
加載css是要兩個加載器,一個是style-loader,一個是css-loader樣式文件默認加載到head里面。
我們來看一個小例子
|__static |__css |__app.css |__app.js |__ index.html |__webpack.config.js
app.css
h1{ background:red; width:100px; height:100px; color:blue;}app.js
require('./css/app.css')document.write('<h1>hello connie</h1>')index.html
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Title</title></head><body><script type="text/javascript" src="dest/dest.js"></script></body></html>
webpack.config.js
module.exports = { entry:'./static/app.js', output:{ filename:'dest/dest.js' }, module:{ loaders:[ { // 配置正則表達式,查找后綴為.css文件 test://.css$/, // 配置加載器,用!符號級聯 loader:'style-loader!css-loader' } ] }}注意:test參數是正則表達式,不需要加引號,如果寫成test:“/.css$/”會報錯!!!
圖片加載器
在webpack,圖片資源也可以被看成是一個模塊,因此也可以用require去加載它們。
但是加載這些圖片,我們需要圖片加載器,圖片加載器叫url-loader
圖片加載比較特殊,有兩種加載方式
在webpack中,我們可以在url-loader中定義個limit參數,來決定采取哪種方式引入。
這句話的意思是,當圖片小于2KB的時候,我們采取內嵌式加載圖片
當圖片大于2kb的時候我們采取外鏈式。
app.css
div{ height: 200px; width: 200px;}.test1{ background-image: url("./images/test1.png");}.test2{ background-image: url("./images/test2.jpg");}.test3{ background-image: url("./images/test3.png");}webpack.config.js
module.exports = { entry: './static/app.js', output: { filename: 'dest/dest.js' }, module: { loaders:[ { // 圖片加載器 test://.(png|jpg|gif|jpeg)$/, loader:'url-loader?limit=2048' }, { test://.css$/, loader:'style-loader!css-loader' } ] }}圖片加載需要安裝url-loader和file-loader
npm install url-loadernpm install file-loader
再次查看dest.js

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。
新聞熱點
疑難解答