如何在Svelte / Sapper应用程序中包含JQuery?

时间:2019-09-04 16:15:49

标签: svelte

不幸的是,有许多组件仍需要我使用JQuery。

在Svelte / Sapper中执行此操作的最佳方法是什么?我应该使用ES6导入,修改汇总还是最好的方法?

例如,我需要包括来自DevExpress或Kendo UI的数据透视表,网格,调度程序等。

我可以在template.html文件中全局引入JQuery并使其正常工作,但是我确信这不是最好的方法。

2 个答案:

答案 0 :(得分:2)

将它作为<script>包含在template.html中就可以了。或者,做

import jQuery from 'jquery';

使用它的任何组件或模块中。

答案 1 :(得分:0)

window.$已被保留,因此您必须修补库
使用jQuery in noconflict mode,例如

sed -E 's/(\W?)\$(\W)/\1jQuery\2/g' library.js >library.noconflict.js

$(替换为jQuery(,将$.替换为jQuery.

(\W?)匹配可选的非单词char(空格,括号),
避免将func_$(替换为func_jQuery(

\$(\W)$($.$)$ 或...匹配。

就我而言,我不得不修补goldenlayout.js 1.5.9版,例如

sed -E 's/(\W?)\$(\W)/\1jQuery\2/g' \
node_modules/golden-layout/dist/goldenlayout.js \
>src/goldenlayout-1.5.9.noconflict.js

还必须替换

(function($){
// ....
        define( [ 'jquery' ], function( jquery ) {
            $ = jquery;
            return lm.LayoutManager;
        } ); // jshint ignore:line
// ....
} );})(window.$);

使用

(function(){
// ....
        define( [], function() {
            return lm.LayoutManager;
        } ); // jshint ignore:line
// ....
} );})();

在运行sed之前避免变量阴影
在这种情况下,本地jQuery与全局window.jQuery

sed可能替换太多(字符串内容)
因此理想情况下进行AST转换

// tools/patch-goldenlayout.js

// pnpm i -D acorn estree-walker magic-string

const input_file = "../node_modules/golden-layout/dist/goldenlayout.js";
const output_file = "../src/goldenlayout.noconflict.js";

const id_search = '$';
const id_replace = 'jQuery';

const acorn_parse = require("acorn").parse;
const estree_walk = require("estree-walker").walk;
const magicString = require("magic-string");
const fs = require("fs");

const code_old = fs.readFileSync(input_file, 'utf8');
let code = new magicString(code_old);

const ast = acorn_parse( code_old, {
    sourceType: 'module', ecmaVersion: 11 /* year 2020 */ });

estree_walk( ast, {
  enter: function ( node, parent, prop, index ) {
    if (node.type == 'Identifier' && node.name == id_search) {
      code.overwrite(node.start, node.end, id_replace);
    }
}});

fs.writeFileSync(output_file, code.toString());