Estus Flask
Estus Flask

Reputation: 222528

$ global as imported 'jquery' module with Webpack

I have @types/jquery package installed and global jQuery that is loaded separately from Webpack bundle.

This may be changed later, and I want to use import * as $ from 'jquery' wherever jQuery is used. I don't want real jquery package to be installed and bundled, only `@types/jquery' to provide TypeScript with jQuery types.

Basically I want

import * as $ from 'jquery';

to be transpiled to

var $ = window.$;

I tried

  {
    test: require.resolve('jquery'),
    use: 'exports-loader?$=window.$'
  }

but it fails because there is no real jquery module:

Module not found: Error: Can't resolve 'jquery' in '.../src'

How can this be achieved?

Upvotes: 1

Views: 84

Answers (1)

Nathan Friend
Nathan Friend

Reputation: 12814

It sounds like you're looking for the externals Webpack option:

https://webpack.js.org/configuration/externals/

The externals configuration option provides a way of excluding dependencies from the output bundles. Instead, the created bundle relies on that dependency to be present in the consumer's environment.

Conveniently, the example in link above uses jQuery for demonstration:

webpack.config.js:

externals: {
    jquery: 'jQuery'
}


application code:

import * as $ from 'jquery';

$('.my-element').animate(...);


When using this option, you can safely install jquery as a dependency without it ending up in your output bundle.

Upvotes: 1

Related Questions