Webpack - sass 加载程序找不到图像

Webpack - sass loader cannot find images

sass loader 文档说:"If you're just generating CSS without passing it to the css-loader, it must be relative to your web root"。 所以我按照它说的做了,我在我的 project root 中有我的 index.html,然后我试图从我的 scss 文件加载一个 image。 现在我有 2 个错误:1) 来自 Chrome's consoleCannot find module "./img/header.jpg"。 2) 来自我的 terminal

ERROR in ./~/css-loader!./~/sass-loader!./~/resolve-url-loader!./public/css/header.scss
Module not found: Error: Cannot resolve 'file' or 'directory' ./img/header.jpg in C:\Web-Development\React\Portfolio\public\css
 @ ./~/css-loader!./~/sass-loader!./~/resolve-url-loader!./public/css/header.scss 6:64-91

webpack.config.js

module.exports = {
    entry: './main.jsx',
    output: {
        filename: './public/js/build/bundle.js'
    },
    module: {
        loaders: [
            {
              test: /\.jsx?$/,
              exclude: /(node_modules|bower_components)/,
              loader: 'babel',
              query: {
                  presets: ['react', 'es2015']
              }
          },
          {
              test: /\.scss$/,
              loaders: ["style", "css", "sass", "resolve-url"]
          },
          {
            test: /\.jpg$/,
            loader: "file?name=[path][name].[ext]"
          }
        ]
    }
};

如果我看到我的代码,我可以清楚地看到我的 css 位于 <head> 中,所以我已经将图像的路径指向我的根目录,如文档所述,但仍然不能修复它。

更新: 我已经安装了 file-loader 并按照说明进行操作,现在我在控制台中收到此错误:GET http://localhost:3000/public/img/header.jpg 404 (Not Found) - jquery.js:9119

据我所知,您实际上是在使用 css 加载器 ("style", "css", "sass", "resolve-url")("css" 部分是 "css-loader")

在您的 sass 文件中,您应该 link 使用来自您正在编辑的 sass 文件的相对路径访问图像。

styles
 - somefile.scss
 - another.scss
images
 - someImage.jpg

在 somefile.scss 中,您应该 link 像这样对您的图像进行处理:

background-image: url("../images/someImage.jpg);

请注意,如果您希望 webpack 将这些图像移动到您的分发文件夹(如果您使用的是这样的系统),您将需要 file-loader 之类的东西来复制这些文件。

如果您的图片已经在您需要的位置,您可以使用 ignore-loader。文件加载器会将文件复制到您的输出文件夹。

为了解决这个问题,我上传了这个webpack extremly basic configuration来开始我的项目,希望它能帮助遇到这个问题的每个人。当然欢迎大家提出建议。