我可以使用ES6 / 2015模块导入在“全局”范围内设置引用吗?

JavaScript Webpack

阿飞

2020-04-03

在这种情况下,我尝试导入一个现有的库(我将troublesome使用Webpack / Babel FWIW对其进行调用),并且它具有对它的全局引用jQuery,我正在尝试使用模块语法来解决它。

我已经通过以下方式将jquery成功导入到模块的“本地”范围中:

import jQuery from 'jquery'

所以我尝试了:

import jQuery from 'jquery'    
import 'troublesome'

但也许并不奇怪,我jQuery is not a functiontroublesome.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"
      }
    ]
  }

第3925篇《我可以使用ES6 / 2015模块导入在“全局”范围内设置引用吗?》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

2个回答
西门 2020.04.03

Shimming很好,有多种解决方法,但是按照我在这里回答,最简单的实际上是恢复使用require加载需要全局依赖的库-然后确保您的窗口。分配是在该require语句之前,并且它们都在您其他导入之后,并且您的订购应保持原样。此问题是由Babel吊装进口引起的,因此它们都在任何其他代码之前执行。

逆天十三蛋蛋 2020.04.03

填充模块是一种方法:http ://webpack.github.io/docs/shimming-modules.html

我从页面引用:

插件ProvidePlugin

该插件使模块可以在每个模块中用作变量。仅在使用变量时才需要该模块。

示例:使$和jQuery在每个模块中可用,而无需编写require("jquery")

new webpack.ProvidePlugin({
  $: "jquery",
  jQuery: "jquery",
  "window.jQuery": "jquery"
})

要将其与webpack-config一起使用,只需将此对象添加到配置中名为plugins的数组中即可:

// the plugins we want to use 
var plugins = [
   new webpack.ProvidePlugin({
      $: "jquery",
      jQuery: "jquery",
      "window.jQuery": "jquery"
   })
];

// this is your webpack-config
module.exports = {
    entry: ...,
    output: ...,
    module: ...,
    plugins: plugins
}

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android