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

Webpack - sass loader cannot find images

本文关键字:图像 找不到 程序 加载 Webpack-sass      更新时间:2023-09-26

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。现在我有两个错误:1)来自Chrome's console:Cannot 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加载器")

在sass文件中,您应该使用正在编辑的sass文件的相对路径链接到图像。

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

在somefile.scss中,您应该链接到您的图像,如下所示:

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

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

如果您的图像已经位于需要它们的位置,则可以使用忽略加载器。文件加载器会将文件复制到输出文件夹中。

为了解决这个问题,我上传了这个webpack极其基本的配置来启动我的项目,我希望它能帮助所有遇到这个问题的人。建议当然都是受欢迎的。