E
E
evilpython2020-01-27 02:18:00
JavaScript
evilpython, 2020-01-27 02:18:00

How to customize SVG to HTML with Webpack?

The problem is the following: svg images are not loaded if they are inserted into html via img.

Example: The loader loads all other images normally. webpack config:
<img src="img/picture.svg">



const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const OptimizeCssAssetsPlugin = require("optimize-css-assets-webpack-plugin");
const TerserJSPlugin = require("terser-webpack-plugin");
const ImageminPlugin = require('imagemin-webpack-plugin').default;
const CopyWebpackPlugin = require("copy-webpack-plugin");
const { CleanWebpackPlugin } = require("clean-webpack-plugin");
const HtmlWebpackInlineSVGPlugin = require('html-webpack-inline-svg-plugin');

const isDev = process.env.NODE_ENV === 'development';
const isProd = !isDev;

const optimization = () => {
  const config = {
    splitChunks: {
      chunks: "all"
    }
  };

  if (isProd) {
    config.minimizer = [new OptimizeCssAssetsPlugin(), new TerserJSPlugin()];
  }
  return config;
};


const fileName = ext => isDev ? `[name].${ext}` : `[name].[hash].${ext}`


module.exports = {
  entry: "./src/index.js",
  output: {
    filename: fileName('js'),
    path: path.resolve(__dirname, "dist")
  },
  resolve: {
    extensions: [".js", ".json", ".css"]
  },
  optimization: optimization(),
  devServer: {
    contentBase: path.resolve(__dirname, "dist"),
    port: 4200,
    hot: isDev
  },
  plugins: [
    new HtmlWebpackPlugin({
      filename: "index.html",
      template: "./src/index.html",
      minify: {
        collapseWhitespace: isProd
      }
    }),
    new HtmlWebpackInlineSVGPlugin({
      runPreEmit: true,
    }),
    new MiniCssExtractPlugin({
      filename: fileName('.css')
    }),
    new CopyWebpackPlugin([
      {
        from: "./src/favicon.png",
        to: path.resolve(__dirname, "dist")
      }
    ]),
    new CleanWebpackPlugin(),
    new ImageminPlugin({
      disable: isDev,
      pngquant: {
        quality: '95-100'
      }
    })
  ],
  module: {
    rules: [
      {
        test: /\.html$/i,
        loader: 'html-loader',
      },
      {
        test: /\.css$/,
        use: [
          {
            loader: MiniCssExtractPlugin.loader,
            options: {
              hmr: isDev,
              reloadAll: true
            }
          },
          "css-loader",
          "postcss-loader",
          "group-css-media-queries-loader"
        ]
      },
      {
        test: /\.less$/,
        use: [
          MiniCssExtractPlugin.loader,
          "css-loader",
          "less-loader",
          "postcss-loader",
          "group-css-media-queries-loader"
        ]
      },
      {
        test: /\.scss$/,
        use: [
          MiniCssExtractPlugin.loader,
          "css-loader",
          "sass-loader",
          "postcss-loader",
          "group-css-media-queries-loader"
        ]
      },
      {
        test: /\.(png|jpe?g|gif|svg)$/i,
        loader: "file-loader",
        options: {
          name(file) {
            if (isDev) {
              return '[name].[ext]';
            }

            return '[name].[hash].[ext]';
          },
          outputPath: "images",
          esModule: false
        },
      },
      {
        test: /\.(woff(2)?|ttf|eot|svg)(\?v=\d+\.\d+\.\d+)?$/,
        use: [
          {
            loader: "file-loader",
            options: {
              name: "[name].[ext]",
              outputPath: "fonts"
            }
          }
        ]
      },
      {
        test: /\.svg$/,
        loader: ['svg-inline-loader']
      },
      { test: /\.js$/, exclude: /node_modules/, loader: "babel-loader" }
    ]
  }
};

Answer the question

In order to leave comments, you need to log in

3 answer(s)
K
kovalskiy_dmitriy, 2020-09-09
@kovalskiy_dmitriy

You can try
https://github.com/bhovhannes/svg-url-loader#in-cs...
or
https://github.com/webpack/webpack/issues/6840

A
Alexey, 2021-01-31
@Armer7

At you it tries to be loaded 3 times. Load somewhere once. I used like this and everything loads:

the code
test: /\.(?:ico|png|jpg|jpeg|svg|gif)$/,
        loader: "file-loader",
        options: {
          outputPath: "assets/images",
          name() {
            if (isDev) {
              return "[name].[ext]";
            }
            return "[name].[hash].[ext]";
          },
        },
      },

By the way, postcss-loaderadd this combination. Will add autoprefixes for different browsers:
the code
"css-loader",
    {
      loader: "postcss-loader",
      options: {
        postcssOptions: {
          plugins: [
            [
              "postcss-preset-env",
              {
                browsers: "last 3 versions",
                autoprefixer: { grid: true },
              },
            ],
          ],
        },
      },
    },

Just install postcss-preset-env.

A
Ascanos, 2021-03-22
@Ascanos

If it doesn’t become outdated, then here is
https://www.npmjs.com/package/image-webpack-loader
Woff(2) helped
me?|ttf|eot|svg from here you need to remove svg, and completely remove the last one)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question