Karthik Ramasamy
Karthik Ramasamy

Reputation: 35

Node.js module.export vs export caching

After going through node docs, I understand caching a little bit. Using module.exports{constant_1, constant_2} will cache its assigned value, so everytime when we call require('') it will get the cached value instead of creating a new one.

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

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

But does the caching happen when we use the below syntax? export {constant_1, constant_2} statement as well?

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

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

Upvotes: 0

Views: 1195

Answers (1)

loganfsmyth
loganfsmyth

Reputation: 161477

import {test} from "example_1";

should be

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

like the CommonJS example, but otherwise the caching behavior is similar for ES modules. The node docs for ESM files for instance states

ES modules are resolved and cached as URLs. This means that files containing special characters such as # and ? need to be escaped.

So as long as the an ./example_1.js and another one somewhere else resolve to the same URL, it will be cached as the same module.

Upvotes: 1

Related Questions