[英]How can i expose a jquery plugin on webpack with babel and typescript
我一直在努力使以下代码无法成功工作。
我有很多使用Typescript构建的es6代码。 我将它们编译为使用babel和typescript的js库。 到目前为止一切正常。 在我的库的顶部,我有一个包装器,它使我可以使用jquery扩展快速访问库的主要组件:
require('jquery');
$.fn.extend({
saidashboard : function (options: SAIDashboardConfig) {
let builtEntry: SAIDashboardView;
/* ... some code ... */
return builtEntry;
}
});
我有一个应该用来测试库的测试文件。 在test-empty.js文件中,我加载了一些json描述符,并尝试使用它初始化我的对象
'use strict';
var chai = require('chai');
var $ = require("jquery");
var fs = require('fs');
require('../dist/sai-dashboard');
chai.should();
var newDash;
before( function(done) {
try{
fs.readFile('./tests/resources/descriptors/empty-dashboard.json', 'utf8', function (err,data) {
if (err) {
done(new Error(err));
} else {
var newDashEl = $('<div></div>').addClass('dashboard-test-container');
newDash = newDashEl.saidashboard(JSON.parse(data));
done();
}
});
}catch(e){
done(e);
}
});
我无法停止出现以下错误
Uncaught TypeError: newDashEl.saidashboard is not a function
就像我的$ .fn.extend在与我正在使用的jquery实例不同的jquery实例上调用它一样。
我正在使用启动测试:
mocha-webpack --require setup-test.js --require source-map-support/register --webpack-config webpack.config-test.js tests/test-empty.js
这是setup.js文件:
const JSDOM = require('jsdom').JSDOM;
const { document } = (new JSDOM('')).window;
global.document = document;
global.window = document.defaultView;
window.console = global.console;
Object.keys(document.defaultView).forEach((property) => {
if (typeof global[property] === 'undefined') {
global[property] = document.defaultView[property];
}
});
global.navigator = {
userAgent: 'node.js'
};
和webpack.config-test.js
var nodeExternals = require('webpack-node-externals');
module.exports = {
output: {
// sourcemap support for IntelliJ/Webstorm
devtoolModuleFilenameTemplate: '[absolute-resource-path]',
devtoolFallbackModuleFilenameTemplate: '[absolute-resource-path]?[hash]'
},
target: 'node', // in order to ignore built-in modules like path, fs, etc.
externals: [nodeExternals()], // in order to ignore all modules in node_modules folder
devtool: "cheap-module-source-map" // faster than 'source-map'
};
任何想法?
谢谢
因此,最终与几个严重依赖某些jQuery插件的项目相关的事情是使用暴露加载器和脚本加载器。 以下内容确保了我可以访问jQuery及其相关插件。
// Example of my app.includes.js
require('expose-loader?jQuery!jquery');
require('expose-loader?$!jquery');
// Then require your plugins using the script-loader to execute them
// so they are part of the global jQuery object.
require('script-loader!your/jQuery/plugin/here')
然后,我必须在我的webpack条目app.js中要求app.includes.js
// app.js
require('./app.inlcudes');
更改导入需求不会有任何伤害,您也可以在webpack.config.js规则中包含暴露加载器 。 我有一些非常具体的原因为什么我的需求被内联使用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.