M
M
Mesuti2020-02-03 14:49:49
webpack
Mesuti, 2020-02-03 14:49:49

How to save relative paths for images in Webpack?

How to save relative paths for images in the final project in Webpack?

Example:

/img/1.jpg
/img/folder/2.jpg

The root of the final project /dist/

It should be like this:
/dist/img/1.jpg
/dist/img/folder/2.jpg


And it turns out only like this:

Setting the file-loader:

test: /\.(gif|png|jpe?g|svg)$/i,
 use: [{
  loader: 'file-loader',
  options: {
   // перебор вариантов
   name: '[name].[ext]' // ->  /dist/1.jpg и /dist/2.jpg все в корень папки
   name: '[folder]/[name].[ext]' // ->  /dist/img/1.jpg и /dist/folder/2.jpg создает папки без вложенности
   name: '[path]/[name].[ext]' // ->  /dist/src/img/1.jpg и /dist/folder/2.jpg берет лишний src 
   path: path.resolve(__dirname, 'dist/[folder]'), // -> /dist/1.jpg и /dist/2.jpg все в корень папки
  }
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
darkfriend, 2022-02-20
@Mesuti

Faced a similar problem.
Solved it like this:

output: {
   assetModuleFilename: (path) => {
       if(typeof path.filename !== "undefined" && path.filename.match(/(img)/)) {
           path.filename = path.filename.replace('src/', '');
           return `${path.filename}/[name].[ext]`;
       }
       return '[name].[ext]';
   }
}

As a result, `src` will be removed and will be `/dist/img/1.jpg`, and the standard template will be applied to the other.
If your source directory is different, then specify a different one.
You can also specify a different final path.

D
Dmitry, 2020-02-03
@disappearedstar

https://webpack.js.org/configuration/output/#outpu...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question