airbnb / babel-plugin-inline-react-svg

A babel plugin that optimizes and inlines SVGs for your React Components.
MIT License
474 stars 92 forks source link

Can't work with webpack resolve.alias? #87

Closed wood3n closed 3 years ago

wood3n commented 4 years ago

I have configured resolve.alias in webpack.config.js:

    resolve: {
      alias: {
        "@": path.resolve(__dirname, "src"),
      },
    },

but when i use @ to import a svg file,that will report an error like this image shows:

import View from "@/assets/icons/view.svg";

image

when i change the import path,it will be ok.

import View from "../../assets/icons/view.svg";

I changed this plugin to @svgr/webpack . With the same webpack.config.js,this problem has been solved now.Maybe that's a small bug in babel-plugin-inline-react-svg.😥 That's my webpack version and other package information: image

ljharb commented 3 years ago

That can't work, because a webpack alias is applied long after babel is run. Instead, don't use any webpack aliases, and use a babel transform instead - and then, if it runs before this plugin, everything should work fine.

wood3n commented 3 years ago

That can't work, because a webpack alias is applied long after babel is run. Instead, don't use any webpack aliases, and use a babel transform instead - and then, if it runs before this plugin, everything should work fine.

Thank you for your answers and suggestions, I tried a new babel plugin —— babel-plugin-module-resolver to solve webpack resolve.alias problem.This is my solution:

yarn add babel-plugin-module-resolver -D

and then apply babel-plugin-module-resolver and babel-plugin-inline-react-svg in webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.m?jsx?$/,
        exclude: /(node_modules)/,
        use: {
          loader: "babel-loader",
          options: {
            presets: ["@babel/preset-env", "@babel/preset-react"],
            plugins: [
              "@babel/plugin-proposal-class-properties",
              "inline-react-svg",           // apply babel-plugin-inline-react-svg
           [
                "module-resolver",         //  apply babel-plugin-module-resolver
                {
                  alias: {
                    "@": "./src",
                  },
                },
              ],
          ],
        },
     },
     ...
  }
}
ljharb commented 3 years ago

That should indeed work, as long as the order of the two transforms is correct (i forget if your comment, or the reverse, is correct). Confirm?

wood3n commented 3 years ago

I confirm that, two plugins order is reversed in my previous comment, that works indeed. If use the right order like this, it also works.

plugins: [
  [
    "module-resolver",
    {
      alias: {
        "@": "./src",
      },
    },
  ],
  "inline-react-svg",
],