【问题标题】:How to Include JQuery in a Svelte/Sapper Application?如何在 Svelte/Sapper 应用程序中包含 JQuery?
【发布时间】:2020-01-07 13:54:51
【问题描述】:

有许多组件仍然需要我需要使用的 JQuery(很遗憾)。

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

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

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

【问题讨论】:

    标签: svelte


    【解决方案1】:

    将它作为<script> 包含在template.html 中很好。或者,做

    import jQuery from 'jquery';
    

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

    【讨论】:

    • 添加“import $ from 'jquery';”在 svelte 组件中生成以下错误:“$ 前缀是保留的,不能用于变量和导入名称 src\Pages\Test.svelte”
    【解决方案2】:

    window.$ 在 svelte 中保留,因此您必须修补您的库
    使用jQuery in noconflict mode,比如

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

    用jQuery(替换$(和用jQuery.替换$.

    (\W?) 匹配可选的非单词字符(空格、括号),
    避免将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());
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-04
      • 2020-04-09
      • 1970-01-01
      • 1970-01-01
      • 2019-11-24
      • 2020-11-08
      • 1970-01-01
      • 2021-04-05
      相关资源
      最近更新 更多