Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

关于module.exports的一些见解 #17

Open
yuandaishi opened this issue Apr 21, 2019 · 0 comments
Open

关于module.exports的一些见解 #17

yuandaishi opened this issue Apr 21, 2019 · 0 comments
Labels

Comments

@yuandaishi
Copy link
Owner

1.如下代码:

//b.js
var counter = 3;
module.exports = {
  counter: counter,
  incCounter: function() {
    console.log(counter);
  },
};
//a.js
var mod = require('./b');
console.log(mod)//{counter: 3, incCounter: ƒ}
mod.incCounter();//3
//编译后的一段代码
([function(e, n) {
    e.exports = {
        counter: 3,
        incCounter: function() {
            console.log(3)
        }
    }
}
//b.js
module.exports = {
  counter: 3,
  incCounter: function() {
    console.log(counter);
  },
};
//a.js输出
{counter: 3, incCounter: ƒ}
//counter is not defined,此处报错
//编译后的一段代码
([function(e, n) {
    e.exports = {
        counter: 3,
        incCounter: function() {
            console.log(counter)
        }
    }
}

首先我们要了解一个基本的事实

无论打包过程如何,有依赖关系的文件都会生成一个文件,而生产环境,也没有什么打包关系了,就是我们很熟悉的html,css,js结构的代码。

打包的过程其实就相当于把一段代码编辑之后,插入到另一段代码中。

上面第二端代码之所以报错,就是因为编辑之后,counter并没有一个值。如果我们改成this.counter则不会报错

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant