zoukankan      html  css  js  c++  java
  • NodeJS 中的模块化(CommonJS)

    定义一个 add 模块并暴露出去:

    function add(a,b){
        return a+b
    }
    exports.add = add;
    

    测试文件中引入这个模块,并调用这个模块中的方法:

    const util = require('./util/add')
    console.log(util); //{ add: [Function: add] }
    console.log('1+2=', util.add(1, 2)) //1+2= 3

    expots 暴露出去的模块是一个对象,当一个模块文件中有多个方法时,可以通过 exports 暴露,调用相应的方法和属性更加方便

    function add(a, b) {
        return a + b
    }
    function sub(a, b) {
        return a - b;
    }
    exports.add = add;
    exports.sub = sub;
    

    也可以这样写:

    exports.add=(a, b) => {
        return a + b
    }
    exports.sub = (a, b) => {
        return a - b;
    }
    

      

    使用 module.exports 暴露 sub 模块

    function sub(a,b){
        return a-b;
    }
    module.exports = sub;

    测试引入并调用:

    const util = require('./util/sub')
    console.log(util) // [Function: sub]
    console.log('3-2=', util(3, 2)) //3-2= 1
    

    module.exports 暴露出去的模块,直接暴露这个方法,所以当整个模块中只有对象时,可以通过 module.exports 暴露

    const util={
        add:(a,b)=>{
            return a+b
        },
        sub:(a,b)=>{
            return a-b;
        }
    }
    module.exports=util;
    

    定义在 node_modules 中的模块,引入时,可以不引入完整目录,但文件命名必须是 index.js,否则会报错 模块找不到:

     引入 add 模块,可以执行

    const util = require('add')
    console.log(util); //{ add: [Function: add] }
    console.log('1+2=', util.add(1, 2)) //1+2= 3

    引入 sub 模块,会如下报错:

    解决方法是 在 模块中使用 npm 生成一个配置文件 package.json

    cd 到 sub 目录,npm init --yes 强制生成 package.json

    入口文件会定义成 sub.js

    再次直接引入,就不会报错了

    const util = require('sub')
    console.log(util) // [Function: sub]
    console.log('3-2=', util.sub(3, 2)) //3-2= 1
    

      

  • 相关阅读:
    省选D2T2 滚榜
    CF1516E(第一类斯特林数)
    Atcoder ZEP F题
    Atcoder ARC 115 A~D
    Atcoder ARC 117
    「舞蹈链 DLX 」学习笔记
    「FJOI-2021」仰视那片离我远去了的天空。
    「UVA1603」破坏正方形 Square Destroyer
    「网络流」学习笔记
    博客搬家
  • 原文地址:https://www.cnblogs.com/shanlu0000/p/13142087.html
Copyright © 2011-2022 走看看