0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

[Nuxt2(bridge)]CSSでSVGをインラインに展開する

Posted at

CSS(SCSS)内にて、url()で指定されたSVGをインラインでエンコードして展開する方法

動作環境

  • nuxt: ^2.15.8
  • @nuxtjs/composition-api: ^0.32.0

必要なパッケージ

  • vue-svg-loader
  • url-loader

インストール

$ yarn add -D vue-svg-loader url-loader

nuxt.config.js

nuxt.config.jsに次のように追記する

nuxt.config.js
  build: {
    ...

    extend (config, ctx) {
      config.resolve.alias['~@'] = path.resolve(__dirname)
      const svgRule = config.module.rules.find(rule => rule.test.test('.svg'))
      svgRule.test = /\.(png|jpe?g|gif|webp|ogg|mp3|wav|mpe?g)$/i

      config.module.rules.push({
        test: /\.svg$/,
        oneOf: [
          {
            resourceQuery: /^\?vue/,
            loader: 'vue-svg-loader',
            options: {
              svgo: {
                //svgがエンコード時に改変されることを回避
                plugins: [{ removeViewBox: false }] 
              }
            }
          },
          {
            loader: 'url-loader',
            options: {
              limit: 10000, // インラインにするファイルサイズの閾値を設定
              encoding: 'base64', // Base64エンコーディングを有効にする
              esModule: false // CommonJSモジュール形式を使用する
            }
          }
        ]
      })
    }

    ...
  },    

こう書くことで、vueファイル内、CSS内のSVGがwebpackによりエンコードされる

.vueファイル

次のように、svgファイルを指定する

<img src="~@/assets/hoge.svg">

background-image: url("~@/assets/hoge.svg")	
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?