Webpack 文件加载器调整 public 路径

Webpack file-loader adjust public path

我的图像文件夹有以下内容:

module.exports = {
        test: /\.(png|jpe?g|gif|svg)$/,
        include: config.paths.images, // this is: path.resolve(__dirname, '../assets/images')
        loader: 'file-loader',
        options: {
            name: '[path][name].[ext]',
            publicPath: '../',
        }
    };

这就是我的 css 的输出:background-image: url(../images/assets/images/doctor-results/g-map-location.png);

我需要的路径是:background-image: url(../images/doctor-results/g-map-location.png);

基本上从路径中删除前 2 个目录,同时保持相对。

您可以使用string-replace-loader

yarn add --dev string-replace-loader

Perform replacements (plain and regular expression) in the contents loaded by the loader.

      {
        test: /\.css$/,
        use: [
          // ...
          {
            loader: 'string-replace-loader',
            options: {
              search: 'assets/images/',
              replace: '',
              flags: 'g'
            },
          },
        ],
      },

我最终使用了 splitsplice 而不是添加另一个库。

{    
    options: {
        name: config.outputs.image.filename,
        publicPath: (url) => {
            const pathArray = url.split('/');
            pathArray.splice(0, 2);
            const path = pathArray.join('/');
            return `../${path}`;
        },
        emitFile: false
    }
}