модули, область функций и проблемы с jQuery noConflict () - PullRequest
0 голосов
/ 14 октября 2018

Настройка

У меня есть скрипт, который загружает jQuery с использованием noConflict (true) на страницы, на которых уже может быть установлена ​​более старая версия jQuery.Мой скрипт встроен в узел с использованием модулей и упакован в один файл с помощью browserify.

Issue

У меня проблемы с правильным выделением моих функций из других модулей, чтобы сохранить переменную $, установленную через noConflict ().Например, представьте, что сайт уже загрузил jQuery версии 1.8, и мой скрипт загружается на страницу и загружает jQuery v. 3.2

<!-- Client site loads old version of jQuery -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js">
</script>

<!-- Our script loads via ajax as a self executing anonymous function.
Just using this scrip tag as an example -->
<script src="myScript.js"></script>

// Contents of myScript.js is bundled with Browserify and hosted
//on our server.  Here is the pre-Browserify code: 

var otherModule = require('./funcB')

//check version of jQuery and load newer version if necessary
if ((typeof jQuery === 'undefined') || (parseFloat(jQuery.fn.jquery) < 3.0)) {
  //loadScript (not shown) is just a function that adds a script tag via
  //ajax to the site <head>
  loadScript("https://code.jquery.com/jquery-3.2.1.min.js", function(){
      jQuery321 = jQuery.noConflict(true);
      funcA(jQuery321);
  });
  } else {
      funcA(jQuery);
}

var funcA = function($){ 
    $('document').ready(function(){
    
      console.log('jquery in funcA: v' + $.fn.jquery)  
      //outputs:  "jquery in funcA: v3.2.1"
      otherModule.funcB();  
      //outputs: "jquery in funcB: v1.8.1"
      funcC();  
      //outputs: "jquery in funcB: v3.2.1"
      
    })
    
    function funcC(){
      console.log('jquery in funcC: v' + $.fn.jquery)
    }  
}

//code from otherModule --> funcB.js 

exports.funcB = function(){
  console.log("jQuery in funcB: v" + $.fn.jquery)
}

module.exports = exports;

Вопрос Очевидно, что это работает, как и ожидалось, однако есть способ сохранить $ как ссылку на jQuery v3.2.1 в модуле otherModule?Возможно, с преобразованием Browserify?

Перемещение всех моих модулей в funcA так, чтобы функции были должным образом распределены, конечно, было бы огромной головной болью, поэтому, если есть способ обойти это, было бы здорово.Я попытался переместить мои операторы require в funcA, а также попытался передать $ в funcB, и оба не сработали.

Спасибо за вашу помощь!

1 Ответ

0 голосов
/ 16 октября 2018

Спасибо Берги за чаевые!Это привело меня в правильном направлении.Теперь все версии модулей $ in - 3.2.1, а $ в консоли браузера - 1.8.1

Комментарии указывают новый код:

var jQuery321;    //add variable name for exporting

var otherModule = require('./funcB')

//now we set jQuery321 to the proper version of jQuery to export
if ((typeof jQuery === 'undefined') || (parseFloat(jQuery.fn.jquery) < 3.0)) {

  loadScript("https://code.jquery.com/jquery-3.2.1.min.js", function(){
      jQuery321 = jQuery.noConflict(true);
      funcA(jQuery321);
  });
  } else {
      jQuery321 = jQuery;   //added this line
      funcA(jQuery);
}

var funcA = function($){ 
    $('document').ready(function(){
    
      console.log('jquery in funcA: v' + $.fn.jquery)  
      otherModule.funcB();  
      funcC();  
      
    })
    
    function funcC(){
      console.log('jquery in funcC: v' + $.fn.jquery)
    }  
}

export { jQuery321 };   //export proper version of jQuery

//code from otherModule --> funcB.js 

import { jQuery321 as $ } from '/myScript.js';  //add import statement

exports.funcB = function(){
  console.log("jQuery in funcB: v" + $.fn.jquery)
}

module.exports = exports;
...