【问题标题】:Why isn't jQuery able to access this imported global variable?为什么 jQuery 不能访问这个导入的全局变量?
【发布时间】:2019-10-12 19:17:30
【问题描述】:

尝试更改我在 jQuery 中导入的全局定义变量会导致引用错误:

global.js

export var w = window.innerWidth;

main.js

import {w} from './global.js';
console.log(w);
$(document).ready(function(){
    ...
    console.log(w);
    w = window.innerWidth;
    console.log(w);
});

前两个控制台打印出值,但第三个给出了一个

main.js:31 Uncaught ReferenceError: w is not defined

跟 webpack 有关系吗?我在开发工具中看到了这一点:

console.log(_global_js__WEBPACK_IMPORTED_MODULE_3__["w"]);
w = window.innerWidth;
console.log(w);

好像不是同一个变量,但是如何让jQuery设置webpack变量呢?

【问题讨论】:

    标签: javascript jquery webpack es6-modules


    【解决方案1】:

    在 ES6 模块系统中,您不能重新分配从另一个模块导入的值。导入的值对于其他模块是只读的。这就是它的本意。否则消费者会在不知道提供者的情况下改变提供者的价值。

    但是,您可以提供一种方法来改变提供者本身的价值:

    global.js:提供者

    var w = window.innerWidth;
    var changeW = function(newValue) {
       w = newValue;
    }
    export { w, changeW }
    

    在 main.js 中:

    import {w,changeW} from './global.js';
    console.log(w);
    $(document).ready(function(){
    ...
       console.log(w);
       changeW(window.innerWidth); //call method to change value
       console.log(w);
    });
    

    【讨论】:

      猜你喜欢
      • 2020-11-02
      • 2017-08-28
      • 2019-05-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多