18

Doing this:

import $ from 'jquery';

Shows the error

The $ prefix is reserved, and cannot be used for variable and import names svelte(illegal-declaration)
Aneri Emmax
  • 182
  • 1
  • 1
  • 7
  • 4
    You can also `import jQuery from "jquery"` to avoid using the $ shorthand, which is indeed a reserved word in svelte. More generally, check https://stackoverflow.com/questions/34338411/how-to-import-jquery-using-es6-syntax for methods to import jQuery using ES6 syntax. – Thomas Hennes Oct 03 '19 at 13:36
  • Thanks, I figured but what I am trying to do is use a bootstrap component but the problem I am having now is the script runs before the component is mounted so at that point there is no element with the ID I am targeting – Aneri Emmax Oct 03 '19 at 15:44
  • Thanks, I figured but what I am trying to do is use a bootstrap component but the problem I am having now is the script runs before the component is mounted so at that point there is no element with the ID I am targeting – Aneri Emmax Oct 03 '19 at 15:58
  • 1
    https://stackoverflow.com/a/57828618/10679649 – Shaya Ulman Oct 03 '19 at 23:48
  • 1
    @AneriEmmax to address your other issue (component not mounted) you can use svelte's `onMount` lifecycle method. See the official doc here: https://svelte.dev/docs#onMount – Thomas Hennes Oct 04 '19 at 09:50
  • Solution for [SvelteKit](https://stackoverflow.com/questions/71017937/importing-jquery-in-sveltekit/) – lefrost Aug 27 '22 at 10:51

3 Answers3

21

You can just use import as syntax:

import * as $j from 'jquery';

Or as anyName that you can use

nircraft
  • 8,242
  • 5
  • 30
  • 46
  • 7
    Eslint says variable name start with `$` is reserved, thus can't start with `$`, so maybe use `j$`. – Eric May 21 '22 at 09:19
  • This didn't work for me. Iirc it was due to a rollup error saying that $ is reserved. See [my anwer](https://stackoverflow.com/a/73852993/12206312) if you're experiencing the same – Snailedlt Jan 02 '23 at 14:45
14

I noticed that if JQuery is already available globally, then you can access it via window.$ instead of just $ and the svelte compiler won't complain.

CBrown77
  • 517
  • 4
  • 18
4

This should do the trick:

import jQuery from 'jquery'

relevant SO answer

Snailedlt
  • 460
  • 6
  • 14