Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
603 views
in Technique[技术] by (71.8m points)

javascript - Webpack - sass loader cannot find images

The sass loader doc says: "If you're just generating CSS without passing it to the css-loader, it must be relative to your web root". So i did as it tells, I have my index.html in my project root, then I'm trying to load an image from my scss file. Now I have 2 errors: 1) from Chrome's console: Cannot find module "./img/header.jpg". 2) from my 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-DevelopmentReactPortfoliopubliccss
 @ ./~/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]"
          }
        ]
    }
};

If I see my code, I can clearly see that my css lives inside <head> so I've pointed my image's path to my root, as documentation says, but still can't fix it.

UPDATE: I've installed file-loader and followed the instructions, now I get this error in console: GET http://localhost:3000/public/img/header.jpg 404 (Not Found) - jquery.js:9119

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As far as I can see you are actually using the css loader ( "style", "css", "sass", "resolve-url" ) (the "css" part is the "css-loader")

In your sass file(s) you should link to the images using a relative path from the sass file you are editing.

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

in somefile.scss, you should link to your image like this:

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

Do note, that if you want webpack to move those images to your distribution folder (if you are using a system like this) that you will need something like file-loader to copy those files over.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...