How to import a jQuery plugin into a babel app

2019-08-21 12:46发布

问题:

So I have a modern javascript app build using ES6 modules and transpiled by babel.

In this app, I need to use a jQuery plugin for some DOM manipulations. I don't want to globally expose jQuery and then load the plugin code into the document using a script tag. Instead, I want the plugin to be available only inside a module:

import $ from 'jquery';
// some magic importing pluginName

$('#element').pluginName();   // how to make this work? 

Of course plugin is not a module and it needs the $ variable to be present when instantiating.

回答1:

You will need to require the plugin:

import $ from 'jquery';
require('path-to-plugin');

$('#element').pluginName();