【问题标题】:Node.js module.export vs export cachingNode.js module.export 与导出缓存
【发布时间】:2021-06-17 16:14:57
【问题描述】:

在浏览了节点文档之后,我对caching 有了一点了解。使用 module.exports{constant_1, constant_2} 将缓存其分配的值,因此每次调用 require('') 时它都会获取缓存的值,而不是创建一个新值。

example_1.js
const test = 'testValue';
module.export = {test};

example_2.js
const cachedValue = require('../example_1.js');
console.log(cachedValue);

但是当我们使用下面的语法时会发生缓存吗? 也导出{constant_1, constant_2} 语句?

example_1.js
const test = 'testValue';
export {test};

example_2.js
import {test} from "example_1";
console.log(test);

【问题讨论】:

    标签: javascript node.js ecmascript-6


    【解决方案1】:
    import {test} from "example_1";
    

    应该是

    import {test} from "./example_1.js";
    

    类似于 CommonJS 示例,但缓存行为与 ES 模块类似。 node docs for ESM files 例如状态

    ES 模块被解析并缓存为 URL。这意味着文件包含特殊字符,例如 # 和 ?需要转义。

    所以只要./example_1.js 和其他地方的另一个解析到同一个 URL,它就会被缓存为同一个模块。

    【讨论】:

    • 感谢您的解释,所以从技术上讲,两者是相同的,唯一的区别是新的 es6 模板。
    • 缓存方面是的,它们几乎相同。 ES6 导入功能可能更强大,就像您最终可能能够从完整的 URL 导入模块,例如 Deno 支持,但您无法使用 require 做到这一点。
    猜你喜欢
    • 2019-11-03
    • 2021-04-14
    • 2023-01-10
    • 2014-05-01
    • 2011-10-31
    • 2014-03-02
    • 2012-03-17
    相关资源
    最近更新 更多