目錄html
上節:使用pluginswebpack
目錄結構:git
webpack默認只識別js文件,其它文件如圖片、字體、樣式等都須要安裝對應的loader才能識別,本節介紹如何在webpack中處理圖片。github
修改src/index.js,使其在頁面中插入一張圖片:web
import pic from './images/cover.png'; window.addEventListener('DOMContentLoaded', function() { const root = document.getElementById('root'); const img = new Image(); img.src = pic; root.appendChild(img); });
這時執行npm run build, 不出意外會報以下錯誤:npm
提示缺乏可以處理圖片的loader, 如今來改一下webpack配置:
webpack.config.js:segmentfault
// 依賴省略 module.exports = { mode: 'production', entry: './src/index.js', output: { filename: '[name].[contenthash:8].js', path: resolve(__dirname, 'bundles') }, module: { rules: [{ test: /\.(gif|jpg|jpeg|png|svg)$/, use: ['url-loader'] }] }, plugins: [ new HtmlWebpackPlugin({ template: './index.html' }), new CleanWebpackPlugin() ] };
module裏能夠針對不一樣類型的文件配置不一樣的loader,好讓webpack能正確處理。
而後安裝loader:
npm i url-loader file-loader -D
ps:url-loader依賴file-loader瀏覽器
安裝完成後再次 npm run build, 此次就能成功打包app
而後瀏覽器運行 bundles/index.html:svg
ok, 成功插入了一張圖片。
打開控制檯能夠看到,圖片src是個base:64編碼,其實url-loader還有不少配置項,
修改webpack.config.js以下:
url-loader還有不少配置項,修改webpack.config.js以下:
// 省略 module: { rules: [{ test: /\.(gif|jpg|jpeg|png|svg)$/, use: [{ loader: 'url-loader', options: { // 當圖片大於801k時,交給file-loader處理,不然url-loader會把圖片src轉成base64編碼 limit: 801920, // 打包後的文件名 name: '[name].[hash:8].[ext]', // 打包路徑 outputPath: 'images/' } }] }] }, // 省略
詳細用法參考:https://github.com/webpack-co...
下一節:使用loader之打包樣式上