美文网首页
珠峰笔记-JavaScript module:CommonJS

珠峰笔记-JavaScript module:CommonJS

作者: saronic | 来源:发表于2018-12-04 16:07 被阅读7次

    NodeJS 使用 CommanJS 模块系统,简单模拟实现,新建 app.js,内容如下:

    const fs = require('fs')
    
    function req(moduleName) {
        const content = fs.readFileSync(moduleName, 'utf-8')
        const fn = new Function('module', content + '\n return module.exports');
        const module = { exports: {} }
        return fn(module)
    
    }
    const string = req('./m.js')
    console.log(string)
    

    在同目录下新建 m.js, 内容只有一句: module.exports = "hello",运行 app.js, 显示如下:

    lee:apptest$ node app.js 
    hello
    

    相关文章

      网友评论

          本文标题:珠峰笔记-JavaScript module:CommonJS

          本文链接:https://www.haomeiwen.com/subject/naxvcqtx.html