apvarun / toastify-js

Pure JavaScript library for better notification messages
https://apvarun.github.io/toastify-js/
MIT License
2.13k stars 230 forks source link

TypeError: $ is not a function after the app is built with Vite #68

Closed scambier closed 3 years ago

scambier commented 3 years ago

I'm not sure if this issue is for Toastify or Vite, so I'm posting it in both projects.

I'm using Toastify in a Vue 3 app, built with Vite. I have 0 problem during development, but Toastify stops working once the app is built for production.

I have the following code:

import * as Toastify from 'toastify-js'

public static showToast({ text, duration = 5000, backgroundColor }:
    {
      text: string,
      duration: number,
      backgroundColor?: string
    }): void {
    Toastify({
      text,
      duration,
      close: true,
      backgroundColor,
      gravity: 'bottom',
      className: 'darkBlueBorder',
      stopOnFocus: true
    }).showToast()
  }

Once built, the code looks like this (excerpt from the compiled file):

static showToast({
        text: e,
        duration: t = 5e3,
        backgroundColor: s
    }) {
        $({
            text: e,
            duration: t,
            close: !0,
            backgroundColor: s,
            gravity: "bottom",
            className: "darkBlueBorder",
            stopOnFocus: !0
        }).showToast()
    }

It looks like Toastify({/**/}) has been replaced with $({/**/}), but $ is never declared. Each time I call myToastService.showToast(), it throws the error

index.be090574.js:1 TypeError: $ is not a function
    at Function.showToast (index.be090574.js:1)
    at Function.showSuccess (index.be090574.js:1)
    at Proxy.saveChanges (index.be090574.js:1)
scambier commented 3 years ago

Fixed by following https://github.com/rollup/rollup/issues/1267

tl;dr: I needed to import Toastify from 'toastify-js' (not import * as Toastify from 'toastify-js'). Since TypeScript was unhappy with this, I also had to set allowSyntheticDefaultImports to true in my tsconfig.

The issue was clearly stated in the vite build --debug log