据我所知,有几种不同的方法可以在 webpack 中请求图像。
1.使用file-loader和html-loader,然后异步加载图片
文件加载器没有解析您的 html 标记,它只允许您要求特定类型的文件,并且该类型的文件将作为 __WEBPACK_MODULE__。
所以假设你有 html 文件 A,
<!-- htmlA -->
<img src='./image/whatever.png' />
并且您想解析src 属性并自动要求它。
在你的 js 中myJS.js,
var htmlA = require('../views/htmlA.html');
//render htmlA or bind the event, do whatever you want here.
你的 webpack 配置应该设置为,
//webpack.config.js
loaders: [
{
//IMAGE LOADER
test: /\.(jpe?g|png|gif|svg)$/i,
loader:'file'
},
{
// HTML LOADER
test: /\.html$/,
loader: 'html-loader'
}
]
这会将您的whatever.png 打包到您的输出文件夹中。它将被定义为 WEBPACK_MODULE 并异步要求它。 基于 webpack.config 中的 publicPath
Check the example1 from my repo.
2。使用url-loader和html-loader,然后同步加载图片
图片将被编码成base64字符串,并插入到你的模块中。(所以它会被同步加载。)
只需将您的 webpack.config.js 更新到此,
//webpack.config.js
loaders: [
{
//IMAGE LOADER
test: /\.(jpe?g|png|gif|svg)$/i,
loader:'url'
},
{
// HTML LOADER
test: /\.html$/,
loader: 'html-loader'
}
]
Check the example2 from my repo.
3.仅使用 url-loader 并手动要求图像
假设你有MyComponent,并且你想要你的图片,
//myJS
var imgContent = require('./xxx.png');//require the image, with url-loader, you will get the base64 encoded string
//set src with pure js
//var img = document.createElement('img');
//img.setAttribute('src', imgContent); //set it to src
//document.body.appendChild(img);
//set src with React ES5
var MyComponent = React.createClass({
render: function() {
return (
<img src={imgContent} />
);
}
});
这样你的webpack.config 将被设置为这样,
//webpack.config.js
loaders: [
{ test: /\.(png|jpg)$/, loader: 'url?limit=8192' } // inline base64 URLs for <=8k images, direct URLs for the rest
]
Check the example3 from my repo.
附:您可以使用webpack-image-loader 来缩小您的图像。
希望这会有所帮助。