問題描述
Webpack 和 Sass 正確處理 background: url() 圖像,但是在與 webpack‑dev‑server 一起使用時找不到它 (Webpack and Sass correctly processes background: url() image but then it's not found when used with webpack‑dev‑server)
我正在使用 Webpack 2 和 webpack‑dev‑server 以及 Sass 加載器,實際配置:
{
test: /\.scss/,
loaders: [
"style",
{ loader: "css", query: { modules: false, sourceMap: true } },
{ loader: "resolve‑url" },
{ loader: "sass", query: { sourceMap: true } }
]
}
這工作得很好,並且在 background: url() 中引用了圖像
由 webpack 處理並替換為類似 background‑somehash.jpg
的樣式,可以通過鍵入 http://localhost:8080/background‑somehash.jpg 訪問此文件</代碼>。當我使用開發人員工具在樣式背景定義中提供整個 url(包括本地主機)時,它也可以工作......
唯一不起作用的是 webpack 生成的原始 css 看起來像 背景:網址(背景‑somehash.jpg)
。我還嘗試了各種網址,例如 ./
、../
、../../
或 ./images/
來測試 root 的設置是否有所不同。我沒有得到的是該文件在根目錄下很容易獲得......
編輯: 與 extract‑text‑webpack‑plugin
將樣式提取到單獨的真實 styles.css
文件中,它工作得很好。問題是為什麼當從 javascript bundle 提供最終 css 時它不起作用?
澄清:一切都被正確引用,圖像可用,當我使用 extract‑text‑webpack‑plugin
當從 bundle.js
提供完全相同的 css 時,它只是不起作用
參考解法
方法 1:
Things you should check:
Is the referenced image recognized by webpack?
Just delete the image and check if the webpack build fails. If that's the case, it is not an issue with your loader configuration.
Check the requested URL with your browser developer tools
If the request is terminated with a 404:
Check if output.publicPath
(webpack) / contentBase
(webpack‑dev‑server) point to the same location. This is from the browser's perspective (=no absolute file paths)
If you're using a <base>
‑tag, you need to ensure that it does replace the base URL correctly.
(by tomastrajan、Johannes Ewald)
參考文件