jQuery UI $(...)。sortable不是WebPack的函数

时间:2017-07-05 17:29:01

标签: javascript npm webpack

我相信我已经正确设置了所有内容,但我在Webpack中遇到了一个奇怪的问题。

考虑这个简单的app.ts文件:

'use strict';

import $ = require('jquery');
import 'jquery-ui';

$(function() {
    $( "#sortable" ).sortable();
});

一切都很好,但是当网站运行时,它会抱怨Uncaught TypeError: $(...).sortable is not a function。 (sortable是一个jQuery UI函数)。

当我改为链接到CDN托管版本的jQuery和jQuery UI时,一切正常,但是当我使用JS模块和Webpack时它并不起作用。这是为什么?

为什么jQueryUI函数sortable()无法识别?

3 个答案:

答案 0 :(得分:15)

问题是jQuery UI通常会自动拉入所需的组件(这就是它通过CDN链接时的工作原理),但是当它导入时它不起作用作为一个模块(与Webpack一样)。

值得庆幸的是,从jQuery UI 1.11开始,您可以手动拉入所需的任何额外组件,如下所示:

'use strict';

import $ = require('jquery');

require('jquery-ui');
require('jquery-ui/ui/widgets/sortable');
require('jquery-ui/ui/disable-selection');

这里有一些official documentation进一步解释了这一点。

答案 1 :(得分:2)

您使用了错误的ES6导入语法,但如果它是正确的,它仍然无法正常工作。 无法识别sortable,因为$模块中jquery-ui不可用。

此解决方案未经优化,因为您导入整个jquery-ui

npm install --save jquery-ui-bundle

<强> index.js

'use strict';

import 'jquery-ui-bundle';

$(function() {
    $( "#sortable" ).sortable();
});

<强>的WebPack

  plugins: [
      new webpack.ProvidePlugin({
          $: 'jquery',
          jQuery: 'jquery',
          'window.jQuery': 'jquery',
          'window.$': 'jquery'
      })
  ]

答案 2 :(得分:2)

这个答案仅仅是两个有用的其他答案的摘要: Answer 1Answer 2

首先,最好知道jquery-ui团队不维护jquery-ui-distjquery-ui-bundle。所以你可能想避免使用它。不过,从jquery-ui版本1.11开始,您可以要求/导入AMD,而从版本1.12开始,您可以使用npm的官方软件包。

解决方案1:
然后,首选的方法是导入jquery-ui的一部分,例如:

import 'jquery-ui/ui/widgets/draggable';

唯一的缺点是,如果您以前使用过import 'jquery-ui',则现在必须导入要特别使用的每个模块。但这更好,因为它只捆绑你真正需要的进口。

检查其网站上的1.11 AMD support documentation1.12 npm documentation

解决方案2:
但是,如果出于任何原因想要使用单个全局jquery-ui导入,则必须调整webpack配置:

首先,确保webpack知道jquery别名:

...
plugins: [
    new webpack.ProvidePlugin({
      '$':'jquery',
      'jQuery':'jquery',
      'window.jQuery':'jquery',
      'global.jQuery': 'jquery'
    }),
...

然后,帮助webpack解析jquery-ui js位置:

resolve : {
    alias: {
      // bind version of jquery-ui
      "jquery-ui": "jquery-ui/jquery-ui.js",      
      // bind to modules;
      modules: path.join(__dirname, "node_modules"),

然后,确保尽快加载jquery-ui(可能在启动期间?)

var $ = require("jquery"),
        require("jquery-ui");

如果要使用jquery-ui的主题,则必须相应地设置css-loader和file-loader。 (别忘了安装这些装载机):

module: {
    loaders: [
      { test: /\.css$/, loader: "style!css" },
      { test: /\.(jpe?g|png|gif)$/i, loader:"file" },

在下面你输入的jquery和jquery-ui只需添加:

import 'modules/jquery-ui/themes/black-tie/jquery-ui.css';
import 'modules/jquery-ui/themes/black-tie/jquery-ui.theme.css';