webpack6--css 背景圖片處理
阿新 • • 發佈:2018-10-31
當css裡面含有背景圖片,用webpack打包時會報如下錯:
如何處理這個問題呢?
我們需要藉助於 file-loader 和 url-loader 這2個包。
下面具體說一下步驟:
1.安裝 file-loader 和 url-loader
cnpm install --save-dev url-loader file-loader
url-loader:
引入的圖片編碼,生成dataURl
file-loader:
解析url引入,根據我們的配置,將圖片拷貝到相應的路徑,再根據我們的配置,修改打包後文件引用路徑,使之指向正確的檔案。
轉換規則:
1.檔案大小<limit,url-loader將會把檔案轉為DataURL;
2.檔案大小>limit,url-loader會呼叫file-loader進行處理,引數也會直接傳給file-loader
2.在webpack.config.js中,做如下配置:
module:{ rules: [ { test: /\.css$/, use: [ 'style-loader', 'css-loader' ] }, { test:/\.(png|jsp|gif)/, use: [{ loader: 'url-loader', options: { limit: 1024, name:'[path][name].[ext]', outputPath: 'images/', publicPath: 'dist/' } }]//或者你可以簡寫成如下形式: //use: 'url-loader?limit=1024&name=[path][name].[ext]&outputPath=images/&publicPath=dist/', } ] },
引數說明:
limit:轉化成最大編碼後的位元組數
name:表示輸出的檔名規則,如果不新增這個引數,輸出的就是預設值:檔案雜湊。
- 加上[path]表示輸出檔案的相對路徑與當前檔案相對路徑相同,打包後文件中引用檔案的路徑也會加上這個相對路徑
- 加上[name].[ext]則表示輸出檔案的名字和副檔名與當前相同
outputPath:輸出檔案路徑字首。打包到指定的輸出資料夾下
publicPath:打包檔案中引用檔案的路徑字首
3.看一下檔案目錄結構
具體程式碼如下:
index.html:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>index</title> </head> <body> <div class="model"></div> <script src="../dist/index.bundle.js"></script> </body> </html>
base.js:
import css from '../css/common.css';
webpack.config.js:
const path = require('path'); //引入path module.exports = { mode: 'development', entry: { index: path.join(__dirname, 'src/js/index.js'), signup:path.join(__dirname, 'src/js/signup.js'), }, output: { path:path.join(__dirname, 'dist'), filename: '[name].bundle.js', }, module:{ rules: [ { test: /\.css$/, use: [ 'style-loader', 'css-loader' ] }, { test: /\.(png|jpg|jpeg|jsp|gif)/, use: [{ loader: 'url-loader', options: { limit: 1024, name:'[name].[ext]', outputPath: 'images/', publicPath: '../dist/images/' } }] } ] }, }
4.執行 cnpm run start
我們可以看到dist裡面的檔案目錄如下:
瀏覽器開啟顯示如下圖:
完美~~
感謝閱讀~~