如何在 Webpack 中使用 css 中的图像
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35369419/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use images in css with Webpack
提问by user3737841
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:
我正在使用 Webpack 设置进行 React,并且正在努力做似乎应该是一项简单的任务。我希望 webpack 包含图像,并像使用 gulp 一样将它们最小化,但我无法弄清楚。我只想能够像这样在我的 css 中链接一个图像:
/* ./src/img/background.jpg */
body { background: url('./img/background.jpg'); }
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.
我的所有 css/js/img 文件夹都在 src 文件夹中。Webpack 输出到 dist 文件夹,但我不知道如何在那里获取图像。
Here is my webpack setup:
这是我的 webpack 设置:
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
}
};
回答by WitVault
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.
我遇到了类似的问题,发现您可以像其他任何 require 或 import 语句一样使用url-loader
来解析"url()"
CSS 中的语句。
To install it:
要安装它:
npm install url-loader --save-dev
npm install url-loader --save-dev
It will install the loader that can convert resolved paths as BASE64 strings.
它将安装可以将解析路径转换为 BASE64 字符串的加载程序。
In your webpack config file use url-loader in loaders
在你的 webpack 配置文件中使用 url-loader in loader
{
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.
还要确保您正确指定了公共路径和您尝试加载的图像路径。
回答by Saloni Yadav
using background-image: url('./img/background.jpg') in the scss file worked for me, without url-loader. Only had file-loader for .png|.jpg|... etc.
在 scss 文件中使用 background-image: url('./img/background.jpg') 对我有用,没有 url-loader。只有 .png|.jpg|... 等的文件加载器。