Search code examples
javascriptvue.jsvuejs2vue-componentpolyfills

Get conic-gradient polyfill to work with Vue


I'm trying to implement this Polyfill in my Vue.js project:

<script src="https://cdnjs.cloudflare.com/ajax/libs/prefixfree/1.0.7/prefixfree.min.js"></script>
<script src="conic-gradient.js"></script>

I'm using a Vue instantiated with Vue-CLI with single file components and webpack.

The description seems so simple, include two script tags and bam it works.

I've added the conic-gradient NPM package to my project (yarn add conic-gradient) which fetches both the conic-gradient script as well as the required prefixfree.

I've then gone ahead trying a dry import in my main.js:

import 'conic-gradient'

as well as

import conic-gradient from 'conic-gradient'

and then calling:

Vue.use(conic-gradient

I've also tried the dry import in my component (dome.vue)

Nothing seems to render the conic gradient however. What am I doing wrong?


Solution

  • Conic-Gradient is not a Vue plugin, so you can't just do Vue.use with it. Neither an ES6 module (sorry for late notice) so you can't use import ConicGradient..., the author published a failed npm package.

    Since you said your project was generated with Vue-CLI, then you must find the src/main.js file, and place your import ConicGradient from 'conic-gradient' at the top of it.

    And you can start using it like

    import ConicGradient from 'conic-gradient'
    
    new Vue({
        data: {
            gradient: new ConicGradient({
                stops: 'gold 40%, #f06 0',
                repeating: true,
                size: 400
           });
        }
    
    })
    

    Go to your index.html and paste this just before your body closing tag </body> (download that file and serve a local copy instead)

    <script src="https://cdn.rawgit.com/LeaVerou/conic-gradient/609dc5f4/conic-gradient.js"></script>

    Now in your Vue components you can use new window.ConicGradient({ ... })

    A working snippet

    Vue.config.productionTip = Vue.config.devtools = false
    
    new Vue({
      el: '#app',
      data: {
        gradient: new window.ConicGradient({
          stops: 'red, yellow, lime, aqua, blue, magenta, red',
          size: 100
        })
      }
    })
    <script src="https://cdn.rawgit.com/LeaVerou/conic-gradient/609dc5f4/conic-gradient.js"></script>
    <script src="https://unpkg.com/[email protected]"></script>
    
    <div id="app">
      <img :src="gradient.png" style="border-radius: 50%" />
    </div>