esbuild: when importing a js file that has jquery as a dependancy, console returns "jQuery is not defined"

193 views Asked by At

When using esbuild, I can import jQuery into my bundle. After I have imported jQuery I can call it's functions.

However, if I also import a file that has jQuery as a dependancy, then once my page loads I get "jQuery not defined" in the console.

So it appears that jQuery can be imported and used. But files that depend on jQuery are not usable: they cannot see the jQuery object.

Initially I tried to just importing jQuery and then a script that depends on it. That produces the error:

import jQuery  from './jquery-3.7.1.js';
import './otherFile.js';

The next thing I tried was making jQuery available globally immediate after importing it, and before importing the other script, but this also causes the error:

import jQuery  from './jquery-3.7.1.js';
window.jQuery = jQuery;
import './otherFile.js';

So how exactly can I make jQuery available to the files that are dependent on it when I'm using esbuild?

I imagine that this problem extends to other libraries as well: If I'm using esbuild, how do I allow scripts to use their dependencies?

2

There are 2 answers

0
sultan On

I think the problem is in the otherFile.js Maybe the file use global jquery, but import jquery is local var。

You can use script import resolve the problem。 Like

<script src='***/jquery-3.7.1.js>
0
Quentin On

Imports are scoped to the module, not globals.

Globals are best avoided in the first place.

Each module that wants to use jQuery should import it itself.