[英]How can I load image(s) used in sass stylesheet in webpack?
我正在使用Webpack捆綁我的模塊,並在基於反應的應用程序中使用sass進行樣式化。
使用單獨的樣式表我正在設置組件的背景圖像並在index.js
加載該樣式表。 樣式表中的所有樣式都應用於除背景圖像之外的該組件。
這是我的樣本樣式表
$bg-img: url('/img/bg.jpg');
.show {
position: relative;
background: $black $bg-img center center;
width: 100%;
height: 100%;
background-size: cover;
overflow: hidden;
}
解決該問題的一種方法是明確要求圖像,然后為反應組件創建內聯樣式。
img1 = document.createElement("img");
img1.src = require("./image.png");
但是,一旦我的樣式表加載而不是分別要求每個圖像,我想加載我的圖像文件夾中的所有圖像。
我的webpack配置文件是
module.exports = {
devtool: 'source-map',
entry: {
main: [
'webpack-dev-server/client?http://localhost:8080',
'webpack/hot/only-dev-server',
'./src/index.js'
]
},
output: {
path: path.join(__dirname, 'public'),
publicPath: '/public/',
filename: 'bundle.js'
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin()
],
module: {
loaders: [
{
test: /\.jsx?$/,
include: path.join(__dirname, 'src'),
loader: 'react-hot!babel'
},
{
test: /\.scss$/,
include: path.join(__dirname, 'sass'),
loaders: ["style", "css?sourceMap", "sass?sourceMap"]
},
{
test: /\.(png|jpg)$/,
include: path.join(__dirname, 'img'),
loader: 'url-loader?limit=10000'
} // inline base64 URLs for <=10k images, direct URLs for the rest
]
},
resolve: {
extensions: ['', '.js', '.jsx']
},
devServer: {
historyApiFallback: true,
contentBase: './'
}
};
我可能會遺漏一些微不足道的觀點。 任何幫助表示贊賞。
啊......經過長時間的調試,我終於找到了問題。 這是我的愚蠢,因為我掙扎。 我想刪除這個問題,但認為當遇到類似問題時,它會幫助像我這樣的新人。
問題在這里
loader: 'url-loader?limit=10000'
我正在設置文件大小限制為10kb而不知道它的作用。 我加載的圖像大小為21kb ! 當你復制其他一些webpack配置文件時會發生這種情況:) javascript疲勞的跡象!
當使用webpack加載你的css及其訪問的資產時,你的css需要遵循你在JavaScript import
使用的相同模塊命名規則或者require
調用。
假設img
文件夾位於源樹的根目錄中,您應該在scss中像這樣引用它:
// note there is no leading /, which tells "require()" to start from the root of your source tree
$bg-img: url('img/bg.jpg');
或者只是完全相對。 假設你的源代碼是這樣的:
/src/styles.scss
/img/bg.jpg
您的styles.scss
可以使用相對路徑:
// note the path is relative to where the style.scss is in your source tree.
$bg-img: url('../img/bg.jpg');
我有類似的問題,但圖片的擴展名為“.jpeg”。 將擴展名更改為“.jpg”有助於我出於某種原因。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.