Javascript webpack 需要相对图像
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30485183/
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
webpack require relative image
提问by Henrik
I have two files:
我有两个文件:
- ./img/mypic.png
- ./js/help/targets/target.js
- ./img/mypic.png
- ./js/help/targets/target.js
In target.js:
在 target.js 中:
<img src={require("../../../img/target.png")} />
With webpack.config.js:
使用 webpack.config.js:
14 module: {
15 loaders: [
16 { test: /\.js$/, loader: 'jsx-loader?harmony' },
17 { test: /\.css$/, loader: 'style-loader!css-loader' },
18 { test: /\.(png|jpg|jpeg|gif|woff)$/, loader: 'url-loader?limit=8192' },
Which compiles the image into ./[hash].png.
将图像编译为./[hash].png.
Now, I use react-router, so I'm at /help/targets/targetand webpack is giving the image this path /help/targets/[hash].pngwhere hash is a sha1 sum. I would prefer if it gave it the path /[hash].png. Just
现在,我使用react-router, 所以我在/help/targets/targetwebpack 给图像这个路径/help/targets/[hash].png,其中 hash 是一个 sha1 总和。如果它给了它路径,我更愿意/[hash].png。只是
How do I make webpack understand that for this js file, the file path to the image is relative in the same way as in the browser?
我如何让 webpack 理解对于这个 js 文件,图像的文件路径与浏览器中的文件路径是相对的?
采纳答案by Henrik
The trick is to give webpack a config-hint on what to base its paths on:
诀窍是给 webpack 一个关于其路径基于什么的配置提示:
Use:
用:
"output": { "publicPath": "/" }
To tell webpack not to be relative.
告诉 webpack 不是相对的。

