2016-02-10 22 views
8

我使用的WebPack捆绑我的模块,并使用青菜为造型的目的在一个反应​​基础的应用。我怎样才能加载的WebPack在上海社会科学院样式表使用的图像(S)?

使用一个单独的样式表我设置的部件的背景图像和在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: './' 
    } 
}; 

我可能会丢失一些琐碎的点。任何帮助表示赞赏。

回答

13

啊....一个长时间的调试,我终于发现了这个问题之后。这是我的愚蠢,因为我挣扎着。我想删除这个问题,但认为当遇到类似的问题时,它会帮助像我这样的新来者。

问题在这里

loader: 'url-loader?limit=10000'

我设置到文件的10KB大小没有真正知道它做什么限制。而这点我是装的形象是规模21KB!发生这种情况时,你复制一些其他的webpack配置文件:) javascript疲劳的迹象!

+0

啊你想要嵌入在CSS中的图像。很高兴你想出来了。 – Brandon

+3

儿子......谢谢你不删除这篇文章。而且我和你在一起,这是完全不透明的文档写的方式,我认为一切低于10kb将dataurl编码,其他一切都会通过... – motleydev

4

当使用webpack加载您的css及其访问的资产时,您的css需要遵循您在JavaScript importrequire调用中使用的相同模块命名规则。

假设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'); 
+0

我都尝试方式。仍然有相同的问题。在web-pack中有url-loader有问题吗? – WitVault

0

我有类似的问题,但带有'.jpeg'扩展名的图像。由于某种原因,将扩展名更改为'.jpg'。

+0

这并没有提供一个问题的答案。一旦你有足够的[声誉](https://stackoverflow.com/help/whats-reputation),你将可以[对任何帖子发表评论](https://stackoverflow.com/help/privileges/comment);相反,[提供不需要提问者澄清的答案](https://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-c​​an- I-DO-代替)。 - [来自评论](/ review/low-quality-posts/17059336) –

相关问题