【问题标题】:Extend ES6 plugin to jQuery prototype将 ES6 插件扩展为 jQuery 原型
【发布时间】:2016-05-10 06:41:05
【问题描述】:

我想寻求帮助,因为我无法在 ES6 中使用模块和类转换我的经典 jQuery (v2) 插件。

在 ECMAScript 5 中,我们可以像这样将 jQuery 插件附加到 jQuery 原型中:

app.js - 通过 HTML <script> 标签加载的 jQuery

$.fn.myPlugin = function() {};
$('div').myPlugin();

它有效:)。在 ES6 中,我会这样写:

myPlugin.es6:

import $ from 'jquery';

export default class myPlugin extends $ {
 // Could i use constructor() method ???
}

app.es6:

import $ from 'jquery';
import myPlugin from 'myPlugin.es6';

$('div').myPlugin();

最后,它不起作用...
我已经搜索过,之前没有人问过这个问题。
我使用 Babel 将 ES6 转译成 ES5。

【问题讨论】:

  • extends $ 没有意义。你以为它和$.extend({…})的意思一样吗?
  • 如果您正在寻找新的 Javascript 功能,您可能不需要 jQuery。有很多不需要 jQuery 的独立 UI 库。此外,还有一个专门的网站youmightnotneedjquery.com 解释了如何从 jQuery 切换到原生功能。

标签: javascript jquery ecmascript-6 babeljs extend


【解决方案1】:

$.fn 只是一个对象。向$ 的原型添加新属性并没有什么神奇之处。所以,代码$.fn.myPlugin = function() {} 等于$.prototype.myPlugin = function() {}

$.fn === $.prototype; // true

为了能够以标准方式 ($('div').func()) 调用 $ 对象上的函数,您需要将此函数添加到 $ 对象中。

你没有在你的 es6 代码中添加它。

因此,

import $ from 'jquery';

export default class myPlugin extends $ {
 // Could i use constructor() method ???
}

意味着(几乎)

var myPlugin = function() {};

myPlugin.prototype = Object.create($.prototype);

return { default: myPlugin };

我不确定你是否应该扩展 $.fn,但也许你需要它。

import $ from 'jquery';
import myPlugin from 'myPlugin.es6';

意思是

var $ = require('jquery');
var myPlugin = require('myPlugin'); // a reference to the 'export.default' object from 'myPlugin.es6'

因此,$.fn 对象和myPlugin 函数之间没有联系。

您应该在某处创建连接。它可以在像plugins 这样的特殊模块中,您将在其中将所有需要的插件注入到$.fn 对象中:

import $ from 'jquery';
import plugin1 from 'plugin1.es6'; // should contain 'name'
import plugin2 from 'plugin2.es6';
...
import plugin10 from 'plugin10.es6';

[plugin1, plugin2, ..., plugin10].forEach(plugin => $.fn[plugin.name] = plugin);

或者您可以在“myPlugin.es6”中为导出的对象添加一个“初始化”方法,并在首次使用之前调用它:init($) { $.fn.myPlugin = myPlugin; }

等等。

【讨论】:

  • 如果一个函数不是匿名的,它有一个 name 属性。所以你的解决方案似乎非常好!我在Rollup sandbox 上玩过它
  • 我最终在我的代码中做了几乎相同的事情。按名称导出:export const myexport = { init: function ($) { /* code here */ } } 然后import { myexport } from './myexport.es6'; myexport.init($)
【解决方案2】:

您可以像往常一样在 ES6 中的 jQuery 原型上安装新方法。对他们来说什么都没有改变。你不会继承 jQuery,所以使用 classextends 是没有意义的。

// myPlugin.es6:
import $ from 'jquery';

$.fn.myPlugin = function() {
    …
};

// app.es6:
import $ from 'jquery';
import 'myPlugin.es6';

$('div').myPlugin();

【讨论】:

  • 这样做,是不是必须在插件的package.json文件(myPlugin.es6)中将jquery依赖标记为peer dependency?否则,您如何确定您和您的插件的使用者都导入了相同的 $ jQuery 对象?
  • @tonix 是的,如果它是一个单独的库,那将是有意义的。
猜你喜欢
  • 1970-01-01
  • 2016-05-05
  • 2010-11-12
  • 2010-12-25
  • 1970-01-01
  • 2021-12-19
  • 1970-01-01
  • 2011-08-14
  • 1970-01-01
相关资源
最近更新 更多