如何在Webpack中使用css中的图像 [英] How to use images in css with Webpack
问题描述
我正在制作一个带有Webpack设置的React,我正在努力做一些似乎应该是一个简单的任务。我希望webpack包含图像,并尽量减少它们,就像我吞咽一样,但我无法弄明白。我只是希望能够像我这样在我的CSS中链接图像:
I am making a React w/ Webpack setup and am struggling to do what seems like should be a simple task. I want webpack to include images, and minimize them like I with gulp but I can't figure it out. I just want to be able to link an image in my css like so:
/* ./src/img/background.jpg */
body { background: url('./img/background.jpg'); }
我在src文件夹中包含了所有的css / js / img文件夹。 Webpack输出到dist文件夹,但我无法弄清楚如何在那里获取图像。
I have all of my css/js/img folders inside a src folder. Webpack outputs to a dist folder, but I can't figure out how to get images there.
这是我的webpack设置:
Here is my webpack setup:
var path = require('path');
var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
devtool: 'cheap-eval-source-map',
entry: [
'webpack-dev-server/client?http://localhost:8080',
'webpack/hot/dev-server',
'./src/index.js'
],
output: {
path: path.join(__dirname, 'dist'),
// publicPath: './dist',
filename: 'bundle.js'
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new HtmlWebpackPlugin({
template: './src/index.html'
})
],
module: {
loaders: [{
exclude: /node_modules/,
test: /\.js?$/,
loader: 'babel'
}, {
test: /\.scss$/,
loader: 'style!css!sass'
}, {
test: /\.(png|jpg)$/,
loader: 'file-loader'
}]
},
devServer: {
historyApiFallback: true,
contentBase: './dist',
hot: true
}
};
推荐答案
我遇到了类似的问题,发现你可以使用 url-loader
来解决CSS中的url()
语句与任何其他需要或导入语句一样。
I was stuck with similar issue and found that you can use url-loader
to resolve "url()"
statements in your CSS as any other require or import statements.
要安装它:
npm install url-loader --save-dev
它将安装可以将已解析路径转换为BASE64字符串的加载器。
It will install the loader that can convert resolved paths as BASE64 strings.
在您的webpack配置文件中,在加载器中使用url-loader
In your webpack config file use url-loader in loaders
{
test: /\.(png|jpg)$/,
loader: 'url-loader'
}
还要确保正确指定公共路径和正在尝试加载的图像路径。
Also make sure that you are specifying your public path correctly and path of images you are trying to load.
这篇关于如何在Webpack中使用css中的图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!