vue-svg-loader icon indicating copy to clipboard operation
vue-svg-loader copied to clipboard

Vue3 Support

Open milewski opened this issue 3 years ago • 47 comments

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

milewski avatar Aug 18 '20 05:08 milewski

@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.

damianstasik avatar Aug 23 '20 15:08 damianstasik

@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 avatar Sep 07 '20 12:09 sritirunagari

@sritirunagari could you share your webpack config?

damianstasik avatar Sep 07 '20 12:09 damianstasik

@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 avatar Sep 07 '20 12:09 sritirunagari

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

damianstasik avatar Sep 07 '20 12:09 damianstasik

@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 avatar Sep 07 '20 13:09 sritirunagari

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

damianstasik avatar Sep 07 '20 13:09 damianstasik

@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 avatar Sep 07 '20 13:09 sritirunagari

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

damianstasik avatar Sep 07 '20 13:09 damianstasik

@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.

sritirunagari avatar Sep 07 '20 13:09 sritirunagari

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

sritirunagari avatar Sep 07 '20 13:09 sritirunagari

@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 avatar Sep 08 '20 17:09 sritirunagari

@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?

damianstasik avatar Sep 13 '20 20:09 damianstasik

@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 avatar Sep 21 '20 15:09 sritirunagari

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

damianstasik avatar Sep 21 '20 16:09 damianstasik

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.

onyx-blackbird avatar Oct 16 '20 08:10 onyx-blackbird

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

prem-prakash avatar Oct 30 '20 19:10 prem-prakash

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;
}

Tjark-Kuehl avatar Nov 09 '20 18:11 Tjark-Kuehl

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

rightaway avatar Jan 14 '21 06:01 rightaway

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.

Keavon avatar Mar 23 '21 07:03 Keavon

Is there an ETA for the stable release?

EmanueleCoppola avatar Apr 21 '21 11:04 EmanueleCoppola

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");
  },
};

WhyNotHugo avatar Jul 16 '21 16:07 WhyNotHugo

@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');
  }
};

jskitz avatar Jul 27 '21 01:07 jskitz

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 avatar Jul 27 '21 01:07 Keavon

@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?

jskitz avatar Jul 28 '21 22:07 jskitz

@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).

phoenix-ru avatar Aug 20 '21 06:08 phoenix-ru

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

giovannidias1 avatar Aug 26 '21 14:08 giovannidias1

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'

tsiotska avatar Aug 28 '21 20:08 tsiotska

Thank for the hint, vue-loader-v16 fixed that particular issue. I did a few more tweaks, and now I'm stuck again seeing:

 ERROR  Failed to compile with 1 error                                                                                               3:51:30 PM

This relative module was not found:

* ../assets/xmas.svg in ./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/Modal.vue?vue&type=script&lang=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.
 node:internal/process/promises:246
          triggerUncaughtException(err, true /* fromPromise */);
          ^

RpcIpcMessagePortClosedError: Cannot send the message - the message port has been closed for the process 1615.
    at /app/node_modules/fork-ts-checker-webpack-plugin-v5/lib/rpc/rpc-ipc/RpcIpcMessagePort.js:47:47
    at processTicksAndRejections (node:internal/process/task_queues:82:21) {
  code: undefined,
  signal: undefined
}

This is my current 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-16")
      .loader("vue-loader-16")
      .end()
      .use("vue-svg-loader")
      .loader("vue-svg-loader");
  },
};

The file path seems correct (and hasn't changed since the working Vue2 setup):

$ ag xmas.svg
src/components/Modal.vue
18:import XMas from "../assets/xmas.svg";

$ fd xmas.svg
src/assets/xmas.svg

I think my src/assets/svgs.d.ts is also relevant, and should be correct (also unchanged since Vue2):

// From https://vue-svg-loader.js.org/faq.html#how-to-use-this-loader-with-typescript
// Required to avoid TS complaining about the SVGs not being proper modules.
declare module "*.svg" {
  import Vue, { VueConstructor } from "vue";

  const content: VueConstructor<Vue>;
  export default content;
}

Any ideas what's up here?

WhyNotHugo avatar Sep 13 '21 16:09 WhyNotHugo

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

This Jest issue seem to still be a problem - the solution described in the docs simply doesnt work. Its very easy to reproduce, as if you try to run a test using a svg as a component in any project it will fail.

AasmundEndresen avatar Sep 17 '21 13:09 AasmundEndresen