通过相对路径包含图像的正确方法

Correct way to include image via relative path

我已经将 laravel-mix 更新到版本 4.0.12 并且在我使用的 *.scss 线上遇到了损坏的构建包含背景图片的相对路径

我得到了下一个文件结构

resources/
|-assets/
||-img/
|||-background.png
||-sass/
|||-footer.scss

我在footer.scss中的代码是下一个

.footer {
  background-image: url(../img/background.png)
}

我的webpack.mix.js是下一个

const mix = require('laravel-mix');

const resourcesAssets = 'resources/assets/';
const dest = 'public/assets/';

mix
  .copy(`${resourcesAssets}images`, `${dest}images`, false)
  .sass(`${resourcesAssets}scss/footer.scss`, `${dest}css`);

在编译过程中 npm run prod 我得到了

Module build failed (from ./node_modules/css-loader/index.js):
ModuleBuildError: Module build failed (from ./node_modules/resolve-url-loader/index.js):
Error: resolve-url-loader: CSS error
predicate must return an absolute path or the result of calling next()
at file://C:\xampp\htdocs\laravel-project\resources\assets\sass\footer.scss:2:3
at encodeError (C:\xampp\htdocs\laravel-project\node_modules\resolve-url-loader\index.js:218:12)
at onFailure (C:\xampp\htdocs\laravel-project\node_modules\resolve-url-loader\index.js:175:14)
at <anonymous>
    at runMicrotasksCallback (internal/process/next_tick.js:122:5)
    at _combinedTickCallback (internal/process/next_tick.js:132:7)
    at process._tickCallback (internal/process/next_tick.js:181:9)
    at runLoaders (C:\xampp\htdocs\laravel-project\node_modules\webpack\lib\NormalModule.js:301:20)
    at C:\xampp\htdocs\laravel-project\node_modules\loader-runner\lib\LoaderRunner.js:364:11
    at C:\xampp\htdocs\laravel-project\node_modules\loader-runner\lib\LoaderRunner.js:230:18
    at context.callback (C:\xampp\htdocs\laravel-project\node_modules\loader-runner\lib\LoaderRunner.js:111:13)
    at onFailure (C:\xampp\htdocs\laravel-project\node_modules\resolve-url-loader\index.js:175:5)
    at <anonymous>
        at runMicrotasksCallback (internal/process/next_tick.js:122:5)
        at _combinedTickCallback (internal/process/next_tick.js:132:7)
        at process._tickCallback (internal/process/next_tick.js:181:9)

        error  in ./resources/assets/sass/footer.scss

我该如何解决这个问题?

问题太新了"resolve-url-loader": "^3.0.0"

前段时间安装中间版本"laravel-mix": "~3"后,它被添加到package.json.

删除它并重新运行构建帮助我解决了问题。 laravel-mix 在 运行 npm run prod.

之后添加 "resolve-url-loader": "2.3.1"

它是 URL 在 Webpack 中重写的东西,因为 Laravel Mix 构建在 Webpack 之上。对于 CSS 编译,Webpack 重写并优化样式表中的任何 url() 调用。

然而,根据Laravel Docs

Absolute paths for any given url() will be excluded from URL-rewriting. For example, url('/images/thing.png') or url('http://example.com/images/thing.png') won't be modified.

因此,Mix 试图将您的 CSS 重写为某事。喜欢:

.footer {
    background-image: url(/img/background.png?<some-hash-identifier>)
}

在这种情况下,您可以像这样禁用 url(),Mix 将不会触及 footer.scss:[=20 中的 url(../img/background.png) =]

mix.sass(`${resourcesAssets}scss/footer.scss`, `${dest}css`);
    .options({
        processCssUrls: false
    });