Vue-svg-loader: Vue3 Support

Created on 18 Aug 2020  路  28Comments  路  Source: visualfanatic/vue-svg-loader

I think the dependency on template-compiler breaks with vue-3, is there any temporarily workaround?

Docs mention

Most helpful comment

@milewski I just released a new beta version with Vue 3 support, please check it out vue-svg-loader@beta. Please follow the updated configuration docs here: https://github.com/visualfanatic/vue-svg-loader/tree/dev#vue-cli.

All 28 comments

@milewski I just released a new beta version with Vue 3 support, please check it out vue-svg-loader@beta. Please follow the updated configuration docs here: https://github.com/visualfanatic/vue-svg-loader/tree/dev#vue-cli.

@visualfanatic Does the webpack config in the readMe file work for vue-svg-loader@beta ? Because svg doesn't load when I upgraded to beta in my vue-3 app I had set it up using webpack 4

@sritirunagari could you share your webpack config?

@visualfanatic Thanks for getting back. Webpack config I used was :
module: {
rules: [
{
test: /.svg$/,
use: [
'vue-loader',
'vue-svg-loader'
],
}
]
}

It's exactly the same config you mentioned in your readMe file. In fact, I have also something else, I had taken a dump of this : vue-next-webpack and added the config, it still didn't pick up svg unfortunately.

Please let me know if i am not clear.

@sritirunagari could you provide a full configuration file? This snippet looks fine 馃

@visualfanatic Here, it is

const path = require('path')
const webpack = require('webpack')
const { VueLoaderPlugin } = require('vue-loader')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')

module.exports = (env = {}) => ({
  mode: env.prod ? 'production' : 'development',
  devtool: env.prod ? 'source-map' : 'eval-cheap-module-source-map',
  entry: path.resolve(__dirname, './src/main.js'),
  output: {
    path: path.resolve(__dirname, './dist'),
    publicPath: '/dist/'
  },
  resolve: {
    alias: {
      '@': path.resolve(__dirname, 'src'),
    }
  },
  module: {
    rules: [
      {
        test: /\.vue$/,
        use: 'vue-loader'
      },
      {
        test: /\.png$/,
        use: {
          loader: 'url-loader',
          options: { limit: 8192 }
        }
      },
      {
        test: /\.css$/,
        use: [
          {
            loader: MiniCssExtractPlugin.loader,
            options: { hmr: !env.prod }
          },
          'css-loader'
        ]
      },
      {
        test: /\.svg$/,
        use: [
          'vue-loader',
          'vue-svg-loader'
        ],
      }
    ]
  },
  plugins: [
    new VueLoaderPlugin(),
    new MiniCssExtractPlugin({
      filename: '[name].css'
    }),
    new webpack.DefinePlugin({
      __VUE_OPTIONS_API__: 'true',
      __VUE_PROD_DEVTOOLS__: 'false'
    })
  ],
  devServer: {
    inline: true,
    hot: true,
    stats: 'minimal',
    contentBase: __dirname,
    overlay: true
  }
})

@sritirunagari that's weird, are you sure you are using the beta version?

@visualfanatic , here is the dependencies overview from package.json

{ "private": true, "scripts": { "dev": "webpack-dev-server", "build": "webpack --env.prod" }, "dependencies": { "vue": "^3.0.0-rc.9" }, "devDependencies": { "@vue/compiler-sfc": "^3.0.0-rc.9", "babel-loader": "^8.1.0", "css-loader": "^4.2.2", "file-loader": "^6.0.0", "mini-css-extract-plugin": "^0.11.0", "url-loader": "^4.0.0", "vue-loader": "^16.0.0-beta.5", "vue-svg-loader": "^0.17.0-beta.1", "webpack": "^4.42.1", "webpack-cli": "^3.3.11", "webpack-dev-server": "^3.10.3" } }

@sritirunagari this might be actual bug in the loader, not in your config, I will take a look at it later today.

@visualfanatic
Infact when I try to run build script, I get the below error

`Module build failed (from ./node_modules/vue-svg-loader/index.js):
Error: Cannot find module 'svgo'
Require stack:

  • **/vue-next-webpack-preview/node_modules/vue-svg-loader/index.js`

then I had installed svgo dependency, to see if it picks up, but no luck.

@visualfanatic Sure, thank you, I will wait for your update

@visualfanatic I have an update. I guess it would have been some mistake in my project settings. I am using a lerna mono-repo and apparently one of the packages didn't compile as expected. I am able to load svgs now.

However, I still see one more issue, the dependency throws error if I build my app without 'svgo' dependency as mentioned in my previous comment. So you might want to add this to your beta version to support webpack.

There is one more problem I came across when setting up jest to transform svgs as per your link ( click here ). Now that, we don't use template-compiler, what would you suggest from where to pull vueJest() from ?

Thanks in advance.

@sritirunagari Sorry for the delay, I finally found a bit of time to push a new release. I checked it using the vue-next-webpack-preview repo and it works, could you confirm?

@visualfanatic Sorry, I had missed to reply.

Could you mention which issue have you fixed in your new release ? I have report two minor ones.

  • 'svgo' dependency missing
  • svgTransform.js setup for Vue-3 & Jest

@sritirunagari I fixed the missing svgo dependency issue. Could you share a simple repro with the Jest issue?

I am also trying to use this in Vue3 which since a few weeks is officially released. Do we still need to use the vue-loader-v16 or is there an update.
And I'm trying to use this approach, but this also doesn't seem to work in Vue3, any ideas:
https://stackoverflow.com/a/59149533/3737177

EDIT: I just realized the documented approach also doesn't work for me (the file is there):
Cannot find module '@/assets/svg/trash_can_solid.svg' or its corresponding type declarations.

@sritirunagari could you share your working configuration? I was not able to get it to work here.

Using Typescript it doesn't work at all.
The svg types are outdated and doesn't work anymore.
You cannot compile with these errors.

Nvmd its fixable with this.

In Vue3 you need to define the Svg definition file like this

declare module '*.svg' {
    import type { DefineComponent } from 'vue';
    const component: DefineComponent;
    export default component;
}

@visualfanatic Anything we can do to help get a stable version with Vue 3 support out?

declare module '*.svg' {
    import type { DefineComponent } from 'vue';
    const component: DefineComponent;
    export default component;
}

Specifically for people running across this, you will want to add this to an index.d.ts file (any file name ending in .d.ts is fine). Then do one of the two following (the second option is better):

Add this to the top of your TypeScript file which is importing the SVGs:

/* eslint-disable @typescript-eslint/triple-slash-reference */
/// <reference path="../path/to/your/index.d.ts"/>

Or (better), update your project root's tsconfig.json so the "include" array points to your .d.ts file, for example you can add this piece:

{
    "include": [
        "src/**/*.d.ts",
    ],
}

I really hope this library can include these type definitions by default! This wasted about six hours of my life split between a few infuriating hours a month ago and again now upon revisiting it. Very glad I was able to finally solve this though.

Is there an ETA for the stable release?

I also can't quite get this to work, but I'm getting an error I'm not seeing anyone else having:

 ERROR  Failed to compile with 1 error                                                                                                                                                                                                                                              4:06:30 PM

 error  in ./src/assets/upload.svg

Syntax Error: TypeError: Cannot read property 'parseComponent' of undefined


 @ ./node_modules/cache-loader/dist/cjs.js??ref--14-0!./node_modules/babel-loader/lib!./node_modules/ts-loader??ref--14-2!./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader-v16/dist??ref--0-1!./src/components/PhotoManager.vue?vue&type=script&lang=ts 21:0-45 26:18-27
 @ ./src/components/PhotoManager.vue?vue&type=script&lang=ts
 @ ./src/components/PhotoManager.vue
 @ ./src/main.ts
 @ multi ./node_modules/@sentry/webpack-plugin/src/sentry-webpack.module.js ./src/main.ts

 ERROR  Build failed with errors.
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

Any ideas? This is my new vue.config.js:

module.exports = {
  // ...
  chainWebpack: (config) => {
    config.resolve.alias.set("vue", "@vue/compat");

    config.module
      .rule("vue")
      .use("vue-loader")
      .tap((options) => {
        return {
          ...options,
          compilerOptions: {
            compatConfig: {
              MODE: 2,
            },
          },
        };
      });

    const svgRule = config.module.rule("svg");

    svgRule.uses.clear();

    svgRule
      .use("vue-loader")
      .loader("vue-loader")
      .end()
      .use("vue-svg-loader")
      .loader("vue-svg-loader");
  },
};

@visualfanatic I have most everything working, except that I can no longer style any SVG files within my component using Vue 3. I don't know what changed between Vue 2 and Vue 3, but here is my very simple component:

<template>
  <div>
    <CameraIcon />
  </div>
</template>
<script>
import CameraIcon from './camera.svg'
export default {
  components: {
    CameraIcon
  }
}
</script>
<style lang='scss' scoped>
svg {
  path {
    transition: all .2s ease-in-out;
    fill: #c3c3c3;
  }
  &:hover {
    path {
      fill: black;
    }
  }
}
</style>

None of the styling works unless I remove scoped. For example, the hover state does not work. But if I remove scoped, then it works but the stylings bleed into other components. I am on version 0.17.0-beta.2. This behavior is different than what I saw in Vue 2.

Also, I am using Vue CLI and have the following config:

  chainWebpack: config => {
    config.resolve.alias.set('vue', '@vue/compat');

    config.module
      .rule('vue')
      .use('vue-loader')
      .tap(options => {
        return {
          ...options,
          compilerOptions: {
            compatConfig: {
              MODE: 3
            }
          }
        }
      });

    const svgRule = config.module.rule('svg');
    svgRule.uses.clear();
    svgRule
      .use('vue-loader')
      .loader('vue-loader')
      .end()
      .use('vue-svg-loader')
      .loader('vue-svg-loader');
  }
};

Just in case it helps anyone figure this out, I was able to get it working in my project, here is the repo: https://github.com/GraphiteEditor/Graphite and here is the vue.config.js: https://github.com/GraphiteEditor/Graphite/blob/master/frontend/vue.config.js

@Keavon I took a look and I also have it working, but my main problem with the latest, is that I have to remove scoped in all of my CSS to use this library now.

Does anyone have any idea what changed between Vue 2 and Vue 3 that requires me to remove scoped on all of my CSS? This is certainly not just a slap in replacement to what was there. Every module that contains an SVG file that I styled based on different states like hover, I've had to remove scoping. I've also asked this question in the Vue Discord channel, and the suggestion (which I'm doing), is to add a class to every component that includes an SVG file, and remove the scoped so that I can move forward for now. I don't really want to unscope all of my styles to make this work. Anyone else running into this?

@Keavon I took a look and I also have it working, but my main problem with the latest, is that I have to remove scoped in all of my CSS to use this library now.

Does anyone have any idea what changed between Vue 2 and Vue 3 that requires me to remove scoped on all of my CSS? This is certainly not just a slap in replacement to what was there. Every module that contains an SVG file that I styled based on different states like hover, I've had to remove scoping. I've also asked this question in the Vue Discord channel, and the suggestion (which I'm doing), is to add a class to every component that includes an SVG file, and remove the scoped so that I can move forward for now. I don't really want to unscope all of my styles to make this work. Anyone else running into this?

That is the way scoped works in general. It will parse all the classes/elements in your SFC and apply scope for them. Since you don't explicitly use SVG in the template, the scoped will ignore it (no matter if it appears later or not).

i getting the following error after update

in ./Assets/icon/category/administracao.svg?component
Module build failed (from ./node_modules/babel-loader/lib/index.js):
SyntaxError: C:\Users\giova\Documents\Project\Project\Project\Assets\icon\category\administracao.svg: Unexpected token, expected "</>/<=/>=" (1:15)

> 1 | <template><svg xmlns="http://www.w3.org/2000/svg" width="32pt" height="32pt" viewBox="0 0 32 32"><path d="M22.719 2.5l-.375 1.063-.313.906A13.009 13.009 0 0016 3C8.832 3 3 8.832 3 16s5.832 13 13 13 13-5.832 13-13c0-1.695-.344-3.297-.938-4.781l1.125-.406 1.032-.344-.438-1A13.045 13.045 0 0023.72 3zm-7.844 2.563c.043-.004.082.003.125 0V15H5.062c.473-5.242 4.586-9.41 9.813-9.938zm2.125 0c1.55.14 3.016.597 4.313 1.312l-2.25 6.281-.72 2 2-.719 5.845-2.062C26.703 13.148 27 14.539 27 16c0 2.68-.945 5.125-2.531 7.031L17 15.563zm6.781.437a10.797 10.797 0 013.563 3.844l-5.688 2zM5.063 17h10.5l7.468 7.469A10.937 10.937 0 0116 27c-5.75 0-10.434-4.387-10.938-10z"/></svg></template>
    |                ^
    at Object._raise (C:\Users\giova\Documents\Project\Project\Project\node_modules\@babel\core\node_modules\@babel\parser\lib\index.js:798:17)
    at Object.raiseWithData (C:\Users\giova\Documents\Project\Project\Project\node_modules\@babel\core\node_modules\@babel\parser\lib\index.js:791:17)
    at Object.raise (C:\Users\giova\Documents\Project\Project\Project\node_modules\@babel\core\node_modules\@babel\parser\lib\index.js:752:17)
    at Object.unexpected (C:\Users\giova\Documents\Project\Project\Project\node_modules\@babel\core\node_modules\@babel\parser\lib\index.js:3257:16)
    at Object.expectRelational (C:\Users\giova\Documents\Project\Project\Project\node_modules\@babel\core\node_modules\@babel\parser\lib\index.js:3176:12)
    at Object.tsParseTypeAssertion (C:\Users\giova\Documents\Project\Project\Project\node_modules\@babel\core\node_modules\@babel\parser\lib\index.js:8424:10)
    at Object.parseMaybeUnary (C:\Users\giova\Documents\Project\Project\Project\node_modules\@babel\core\node_modules\@babel\parser\lib\index.js:9556:19)
    at Object.parseExprOps (C:\Users\giova\Documents\Project\Project\Project\node_modules\@babel\core\node_modules\@babel\parser\lib\index.js:10882:23)
    at Object.parseMaybeConditional (C:\Users\giova\Documents\Project\Project\Project\node_modules\@babel\core\node_modules\@babel\parser\lib\index.js:10856:23)
    at Object.parseMaybeAssign (C:\Users\giova\Documents\Project\Project\Project\node_modules\@babel\core\node_modules\@babel\parser\lib\index.js:10814:21)

this ocurrers in all my svg files i'm using webpack

I also can't quite get this to work, but I'm getting an error I'm not seeing anyone else having:

 ERROR  Failed to compile with 1 error                                                                                                                                                                                                                                              4:06:30 PM

 error  in ./src/assets/upload.svg

Syntax Error: TypeError: Cannot read property 'parseComponent' of undefined


 @ ./node_modules/cache-loader/dist/cjs.js??ref--14-0!./node_modules/babel-loader/lib!./node_modules/ts-loader??ref--14-2!./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader-v16/dist??ref--0-1!./src/components/PhotoManager.vue?vue&type=script&lang=ts 21:0-45 26:18-27
 @ ./src/components/PhotoManager.vue?vue&type=script&lang=ts
 @ ./src/components/PhotoManager.vue
 @ ./src/main.ts
 @ multi ./node_modules/@sentry/webpack-plugin/src/sentry-webpack.module.js ./src/main.ts

 ERROR  Build failed with errors.
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

Any ideas? This is my new vue.config.js:

module.exports = {
  // ...
  chainWebpack: (config) => {
    config.resolve.alias.set("vue", "@vue/compat");

    config.module
      .rule("vue")
      .use("vue-loader")
      .tap((options) => {
        return {
          ...options,
          compilerOptions: {
            compatConfig: {
              MODE: 2,
            },
          },
        };
      });

    const svgRule = config.module.rule("svg");

    svgRule.uses.clear();

    svgRule
      .use("vue-loader")
      .loader("vue-loader")
      .end()
      .use("vue-svg-loader")
      .loader("vue-svg-loader");
  },
};

You've forgotten to use 'vue-loader-v16' instead of 'vue-loader'

Was this page helpful?
0 / 5 - 0 ratings

Related issues

sashakaralchuk picture sashakaralchuk  路  6Comments

santigarcor picture santigarcor  路  8Comments

dsbert picture dsbert  路  6Comments

MattCCC picture MattCCC  路  6Comments

jdfx picture jdfx  路  7Comments