Home > OS >  Webpack 5 import images and fonts, rewrite url in prod
Webpack 5 import images and fonts, rewrite url in prod

Time:02-06

I need to copy the image and font files to the appropriate folder in the dist directory, the problem is that in the final css file I get the wrong url path. I tried to disable url css-loader then files are not copied at all. Tried adding ~ to url . I need to use asset/resource to copy and paste the correct path in the stylesheet. Various other outdated solutions won't work for me.

MY STRUCTURE

CodePudding user response:

Customize the publicPath to point to the folder from where your static files are served.

CodePudding user response:

I solved my problem by adding publicPath: ".", why is there a dot in quotes? Because I have the path ./ in the url itself, so I add a dot and I can exit the directory.

For fonts, I created a generator that creates a separate folder, paths work on the same principle.

output: {
    path: path.resolve(__dirname, "dist"),
    publicPath: ".",
    assetModuleFilename: "./img/[name].[ext]",
    clean: true,
  },
  
  {
        test: /\.(jpe?g|png|gif|svg)$/i,
        type: "asset/resource",
      },
      {
        test: /\.(woff|woff2|eot|ttf|otf)$/i,
        type: "asset/resource",
        generator: {
          filename: "./fonts/[name][ext]",
        },
      },

  •  Tags:  
  • Related