定义 image-loader

const path = require('path');
const sizeOf = require('image-size');
const fs = require('fs');
 
// scss-loader.js
function loader(content) {
  const regex = new RegExp(/__taomee__image__:\s*url\(([^)]*)\);/, 'g')
  const matches = content.matchAll(regex);
  for (const match of matches) {
    let file = match[1].replace(/@/, path.resolve('src'));
    file = file.trim();
    if (fs.existsSync(file)) {
      let dimension = readFileDimension(file);
      let width = dimension.width / 100;
      let height = dimension.height / 100;
      let replaceStr = `
        background-image: url(${file});
        width: ${width}rem;
        height: ${height}rem;
      `;
      content = content.replace(match[0], replaceStr.replace(/\s/g, ''));
    }
  }
  return content
};
 
/**
 * 
 * @param {String} filePath 
 * @returns {
 *   width: 1000,
 *   height: 1000
 * }
 */
function readFileDimension(filePath) {
  return sizeOf(filePath);
}
 
exports.default = loader;

webpack.config.js 中使用:

{
	test: /\.scss$/,
	use: [
		'css-loader',
		'./loaders/image-loader.js', 
		{
		  loader: "sass-loader",
		  options: {
			api: "modern",
		  },
		}
	]
},