如何在另一个js文件中使用其他js文件的变量或function,在客户端是不支持的。

  1. 导出
  2. //a.js
  3. var a = 10;
  4. module.exports = a;
  1. 导入
  2. //b.js
  3. var a = require("./a.js");
  4. console.log(a);

1-1

  1. 导出
  2. //a.js
  3. var a = 10;
  4. function show(){
  5. console.log("show")
  6. }
  7. module.exports = {
  8. a,
  9. show
  10. }
  1. 导入
  2. //b.js
  3. const obj = require("./a.js");
  4. console.log(obj)
  5. Tips:一个文件中只能有一个module.exports
  6. module.exports == exports

1-2 exports导出 不推荐

Tips:不支持字面量的形式

  1. var a = 10;
  2. function show(){
  3. console.log("show")
  4. }
  5. /* exports */
  6. console.log(module.exports == exports)
  7. /* 不推荐 */
  8. exports.a = a;
  9. exports.show = show;