lefrost
lefrost

Reputation: 581

Importing jQuery in SvelteKit

How do I import jQuery in SvelteKit (with TypeScript support)?

const jq = window.$ as one would do in Svelte runs into window is not defined.

Update as of Aug 2022: No longer running into window is not defined. See selected answer.

Upvotes: 0

Views: 3630

Answers (2)

lefrost
lefrost

Reputation: 581

Make jQuery available globally. So in app.html:

<!-- Example. Update to latest jQuery versions. -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>

Then in .svelte files, access jQuery via window.$:

import { onMount } form 'svelte';
const jq = window.$;

onMount(() => {
  // Use jQuery as you wish. For example:
  jq(`#draggable-div`).draggable();
});

Upvotes: 0

Syed M Sohaib
Syed M Sohaib

Reputation: 412

You can just use import as syntax:

import * as $jq from 'jquery';

Or you can do like this

import { onMount } from 'svelte';
import js from 'jquery';

onMount(() => {
  window.jq = js;
});

Upvotes: 2

Related Questions