feng xiaohan

Node模块(module)的导出导入

const requestHandler = () => {};

导出

默认导出

  • 整体模块导出

    module.exports = requestHandler;
    

    该导出方式的导出函数会作为整个文件的导出结果,不支持重命名。

  • 对象表示导出

    module.exports = {
      handler: requestHandler,
      someText: "导出的一些字符串",
    };
    

    该导出方式可以一次性导出多个变量,支持重命名。

  • 简写默认导出

    exports = {
      someText: "导出的一些字符串",
    };
    

注意默认导出的内容不会出现在全局对象exports,只有命名导出的内容才会出现。

命名导出

  • 属性表示导出

    module.exports.handler = requestHandler;
    module.exports.someText = "导出的一些字符串";
    

    该导出方式可以一条一条导出,支持重命名。

  • 属性表示导出(快捷方式)

    exports.handler = requestHandler;
    exports.someText = "导出的一些字符串";
    

注意:命名导出(exports.xxx)和默认导出(exports)不可以同时使用。如果一个模块中同时使用了命名导出和默认导出,则命名导出将被忽略,只有默认导出的内容会被导出。

导入

使用require导入我们导出函数或属性的文件:

const routes = require("./routes");
  • 对于整体模块导出的导入

    // routes就是requestHandler
    console.log(routes);
    
  • 对于其他导出的导入

    // 需要用.来对应
    console.log(routes.handler);
    console.log(routes.someText);