我有一个用作库的es6 js文件。如你所见,js文件依赖于jquery。我正在使用Webpack。
在JS文件中,我在下面的行中导致_interopRequireWildcard在我下面复制的最终es5代码中。由于jquery不是esModule,在评估条件$('span.hot').each(function(i, elem) {
bilist[i] = $(this).text();
});
之后,jQuery函数被复制到Object。我也在使用这个代码与typescript。它适用于Typescript但与es6失败。
ES6代码段
obj && obj.__esModule
透明的ES5代码
import * as $ from 'jquery';
let setupObject = function setupObject(element) {
let aButton = $(dropdownButtonSelector); //Fail's here with error
//Uncaught TypeError: $ is not a function
}
exports default setupObject;
答案 0 :(得分:2)
Your import takes all available imports and wraps them in an object:
import * as $ from 'jquery';
So $
would probably look something like this:
{Animation: function Animation(...),Callback: function (...), Deferred: function(...), default: function(selector, context){}, fn: Object[0], .... }
Thus your TypeError
:
Uncaught TypeError: $ is not a function
(See: http://www.2ality.com/2014/09/es6-modules-final.html#more_on_importing_and_exporting)
Try using the following statement instead, it will only import the default
export:
import $ from 'jquery';
Since your jQuery
probably still has CommonJS exports (module.exports
), its exports will automatically be mapped to export default
by babel.
答案 1 :(得分:1)
我终于得到了同样的文件,使用es6和typescript。我实际上将代码更改为使用require('jquery')
而不是import $ from 'jquery'
。所以这是最终的代码
最终的ES6代码段
var $ = require('jquery');
let setupObject = function setupObject(element) {
let aButton = $(dropdownButtonSelector); //Fail's here with error
//Uncaught TypeError: $ is not a function
}
exports default setupObject;
带有Webpack的透明ES5代码,将其用作es6
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var setupObject = function setupObject(element) {
var $ = __webpack_require__(1);
var aButton = $(dropdownButtonSelector);
...
};
exports.default = setupDropdown;
带有Webpack的透明ES5代码,将其用作打字稿
!(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__, exports], __WEBPACK_AMD_DEFINE_RESULT__ = function (require, exports) {
"use strict";
var setupObject = function setupObject(element) {
var $ = __webpack_require__(10);
var aButton = $(dropdownButtonSelector);
...
}
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = setupDropdown;
}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));