SASS变量在url()中引用图片路径触发Module not found错误
Hey there, let's break down why your SASS variable isn't working for your background image path and how to fix it!
The Root of the Problem
When you store a path as a plain SASS string variable, the compiler outputs it as raw text in your final CSS. Tools like Webpack can't parse this raw string during the build process—they need to recognize the path as a resource to resolve during the pre-compilation stage. That's why you're getting that "Module not found" error.
Solution 1: Use SASS Interpolation
The key is to use SASS interpolation (#{}) to inject your variable into the url() function properly. This tells the compiler to treat the variable's value as a resolvable path, not just a string.
Here's how to do it:
// Option 1: Use ~ to reference your src directory (works with Webpack) $loader-img-path: '~assets/loader.png'; // Option 2: Use a relative path to your SCSS file // If your SCSS is in src/styles/ and images in src/assets/, use: // $loader-img-path: '../assets/loader.png'; .loader { background-image: url(#{$loader-img-path}); }
The ~ prefix tells Webpack to resolve the path from your project's root (usually the src directory), just like how you'd import files in JavaScript.
Solution 2: Fix Compass's image-url Output
If you're using Compass's image-url() function and it's just outputting the raw function text instead of resolving the path, you need to configure your SASS setup to recognize your asset directory.
For Webpack's sass-loader, add this to your configuration:
module.exports = { module: { rules: [ { test: /\.scss$/, use: [ 'style-loader', 'css-loader', { loader: 'sass-loader', options: { sassOptions: { loadPaths: ['src/assets'], // Point to your assets folder functions: { 'image-url($url)': function(url) { // Resolve the path and output a proper url() return new sass.types.String(`url(${this.resolve(url.getValue())})`); } } } } } ] } ] } };
This setup tells Compass where your assets live and converts the image-url() call into a resolvable url() for Webpack.
Solution 3: Ensure Your Loader Configuration is Correct
Don't forget to set up url-loader or file-loader to handle image files in your Webpack config. This is what lets Webpack process and bundle your images:
module.exports = { module: { rules: [ { test: /\.(png|jpg|gif)$/, use: [ { loader: 'url-loader', options: { limit: 8192, // Convert small images to base64 name: '[name].[hash:7].[ext]', outputPath: 'assets' // Where bundled images go } } ] } ] } };
Quick Recap
- Use
#{}interpolation to inject your path variable intourl()so Webpack can resolve it. - Use
~or relative paths to make sure the path points correctly to your image. - Configure
sass-loaderto handle Compass'simage-url()if you're using it. - Double-check your image loader setup to ensure Webpack can process image files.
内容的提问来源于stack exchange,提问作者Ikhlak S.

