Search code examples
javascripttypescriptvue.jsstripe-paymentsnuxt.js

Cannot use Stripe with nuxt and typescript


I've got a problem, I'm trying to implement Stripe on my nuxt/typescript projet, I use vue-property-decorator as well.

Here's my head in nuxt.config.js

head: {
        title: process.env.npm_package_name || '',
        meta: [
            {charset: 'utf-8'},
            {name: 'viewport', content: 'width=device-width, initial-scale=1'},
            {hid: 'description', name: 'description', content: process.env.npm_package_description || ''}
        ],
        script: [{
            src: "https://js.stripe.com/v3/",
            type: "text/javascript"}],
        link: [
            {rel: 'icon', type: 'image/x-icon', href: '/favicon.ico'}
        ]
    },

My component:


<script lang="ts">
    import {Component, Prop, Vue} from "vue-property-decorator";
    import {Subscription} from "~/models/Subscription";

    @Component({
        components: {}
    })
    export default class PaymentForm extends Vue {

        @Prop()
        public subscription: Subscription;

        mounted() {
            let stripe = Stripe(`MY PUBLIC KEY`),
            elements = stripe.elements(),
            card = undefined;
            card = elements.create("card");
            card.mount(this.$refs.card);
        }
    }
</script>

But I got this error

Cannot find name 'Stripe'. Did you mean 'stripe'?

So I can't build my project, can you help me? I tried to just write this component in js and it worked but I'd like to keep my ts.

Thanks!


Solution

  • Stripe property is accessible on client side as window.Stripe after sdk script is loaded. During development TypeScript has no reference for global variable Stripe.

    One way to fix it, is to create definitions for Stripe property on global window object.

    This can be done by creating (or extending if exists) type definitions of Window class. In type definitions folder create a file global.d.ts (or any other) with following code:

    interface Window {
      Stripe: any;
    }
    

    This will extend default Window class and allow to use Stripe without errors in your code like this:

    const stripe = window.Stripe('MY PUBLIC KEY')
    

    Note that this will not provide completion for sdk methods and properties.