node-module

208 阅读1分钟

基础用法

文件 main.js

var hello = require('./hello');
hello.world();

// 或
var {world} = require('./hello');
world();

文件hello.js

exports.world = function() {
    console.log('Hello World');
}

// 或是

function world() {
    console.log('Hello World');
}

module.exports = {world};

node main.js运行,打印 Hello World

即文件引用和导出有两种方式

  • 引用
var {world} = require('./hello');

// 即
var _fs = require('./hello');
var world = _fs.world
  • 导出
module.exports = ***
exports.***

exports 和 module.exports 的使用

如果要对外暴露属性或方法,就用 exports 就行,要暴露对象(类似class,包含了很多属性和方法),就用 module.exports。

// main.js
var People = require('./hello');
people  = new People();

people.setName('chy');
people.introduce();
// hello,I am chy

// hello.js
function People() {
    var pname;
    this.setName = function (name) {
        pname = name;
    };
    this.introduce = function () {
        console.log('hello,I am ' + pname);
    };
}
module.exports = People;

如果同时使用exports和module.exports会发生什么?

// main.js
var People = require('./hello');
people  = new People();

people.setName('chy');
people.introduce();
People.hello()

// hello.js
function People() {
    var pname;
    this.setName = function (name) {
        pname = name;
    };
    this.introduce = function () {
        console.log('hello,I am ' + pname);
    };
}

module.exports = People;

exports.hello = function () {
    console.log('Hello World');
};

出错 People.hello is not a function

不建议同时使用 exports 和 module.exports。

如果使用 exports 对外暴露属性或方法,再使用 module.exports 暴露对象,会使得 exports 上暴露的属性或者方法失效。 原因在于,exports 仅仅是 module.exports 的一个引用。

module.builtinModules

罗列 Node.js 提供的所有模块名称。

const builtin = require('module').builtinModules;

console.log(builtin)

module.createRequire(filename)

解决 es6Module和commonJs混用

import { createRequire } from 'module';

const require = createRequire(import.meta.url);
const hello = require('/test/hello');
console.log(hello);

module.syncBuiltinESMExports()

module.syncBuiltinESMExports()方法更新内置ESModule的所有活动绑定,以匹配CommonJS导出的属性。它不会从ESModule中添加或删除导出的名称。