对于自定义的文件模块,需要通过文件的路径来对模块进行引入,路径可以是绝对路径,如果是相对路径必须以./../开头。

  1. // 自定义模块
  2. var router = require("./router");

例子

当exports多个属性和方法时,在require导入时,需要于相应的属性和方法名称相同。

  1. // moduleA.js
  2. exports.x = "moduleA.js";
  3. exports.sayHello = function () {
  4. console.log("moduleA.js say hello....");
  5. }

第一种情况:

  1. // index.js 该Js文件导入其他模块
  2. var {y, say} = require("./moduleA.js");// <= Error, 必须与moduleA.js的名称相同
  3. var {x, sayHello} = require("./moduleA.js");
  4. console.log(x); // moduleA.js
  5. sayHello(); // moduleA.js say hello ....

第二种情况:

  1. // index.js
  2. // 使用一个变量接收modeluA.js,会自动封装为一个对象
  3. var moduleA = require("./01.hello");
  4. console.log(moduleA.x);
  5. moduleA.sayHello();