在这种情况下,我尝试导入一个现有的库(我将troublesome
使用Webpack / Babel FWIW对其进行调用),并且它具有对它的全局引用jQuery
,我正在尝试使用模块语法来解决它。
我已经通过以下方式将jquery成功导入到模块的“本地”范围中:
import jQuery from 'jquery'
所以我尝试了:
import jQuery from 'jquery'
import 'troublesome'
但也许并不奇怪,我jQuery is not a function
从troublesome.js
我也尝试过这个:
System.import('jquery')
.then(jQuery => {
window.jQuery = jQuery
})
import 'troublesome'
but, it turns out that System.import
is part of the, so-called, 'module-loader' spec, which was pulled from the es6/2015 spec, so it isn't provided by Babel. There is a poly-fill, but Webpack wouldn't be able to manage dynamic imports accomplished via calls to System.import
anyway.
but... if I call out the script files in index.html like so:
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/troublesome/troublesome.js"></script>
<script src="the-rest-of-my-js.js"></script>
the reference to jQuery
is resolved in troublesome.js
and things are good,
but I would prefer to avoid the script tag route as webpack doesn't manage those.
Can anyone recommend a decent strategy for dealing with scenarios like this?
update
with some guidance from @TN1ck, I was eventually able to identify one Webpack-centric solution, using the imports-loader
The configuration for this solution looks something like this:
//...
module: {
loaders: [
//...
{
test: require.resolve('troublesome'),
loader: "imports?jQuery=jquery,$=jquery"
}
]
}
Shimming很好,有多种解决方法,但是按照我在这里的回答,最简单的实际上是恢复使用require加载需要全局依赖的库-然后确保您的窗口。分配是在该require语句之前,并且它们都在您其他导入之后,并且您的订购应保持原样。此问题是由Babel吊装进口引起的,因此它们都在任何其他代码之前执行。