In webpack, the webpack devtool is usually set to enable the sourceMap feature. If you use resolve-url-loader and sass-loader, when you turn off the sourceMap feature of webpack for production output, you may get an error message like the following.

ModuleNotFoundError: Module not found: Error: Can’t resolve ‘… /… /…/images/abc.png’

After debugging the source code of resolve-url-loader and sass-loader, I found that resolve-url-loader relies on the sourceMap information processed by sass-loader for complex path finding, and the sourceMap switch of sass-loader is webpack global by default.

When webpack’s sourceMap is turned off, resolve-url-loader is unable to determine the real file path for scss files that are @import, because the sourceMap information is missing, and the relative path finding method is therefore disabled. Please refer to the following quoted code for your own analysis.

Explanation: The code references of the above plug-ins are: resolve-url-loader@3.1.1 and sass-loader@8.0.2.

After finding the reason, after analyzing the code logic, we know that opening sass-loader’s sourceMap can solve the problem. The example is as follows.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
rules: [
  {
      test: /\.scss$/,
      use: [
          MiniCssExtractPlugin.loader,
          'css-loader',
          'resolve-url-loader',
          {
              loader: 'sass-loader',
              options: {
                  // implementation: require('sass'),
                  // 须设置为 true,使得 resolve-url-loader 能够得到原始文件信息以尝试各种路径查找(options.join)
                  sourceMap: true,
                  sassOptions: {
                      // sourceMap: path.join(process.cwd(), '/sass.map'),
                      // outFile: pluginDesc,
                      // sourceMapRoot: pwd,
                      // omitSourceMapUrl: true,
                      // sourceMapContents: true,
                      includePaths: [path.resolve(src, './styles/'), path.resolve(pwd, './src/styles/')],
                  },
              },
          },
      ],
  },
]