Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use require.resolve when deleting key in require.cache #520

Closed
ofabel opened this issue Aug 22, 2020 · 4 comments
Closed

Use require.resolve when deleting key in require.cache #520

ofabel opened this issue Aug 22, 2020 · 4 comments

Comments

@ofabel
Copy link

ofabel commented Aug 22, 2020

I would suggest to replace the following line:

delete cache[modulePath];

With this:
delete cache[require.resolve(modulePath)];

Why is this necessary? Packages like https://github.com/vercel/ncc use their own require.cache implementation. This small fix ensures twing's cache to work as expected when bundled with ncc.

@ofabel
Copy link
Author

ofabel commented Aug 22, 2020

Nevermind, a working solution is far more complicated. I solve it by implementing a own cache.

@ofabel ofabel closed this as completed Aug 22, 2020
@ericmorand
Copy link
Member

Awesome. Was it easy? I focused on having the API easy to inherit and extend so let me know if something was more difficult than needed to create your own filesystem cache.

@ericmorand ericmorand reopened this Aug 22, 2020
@ericmorand
Copy link
Member

I reopened the issue. I think that using require.resolve may be a better approach anyway. Not sure I can find a test to demonstrate this though. I keep the issue opened to not forget giving it a try.

@ofabel
Copy link
Author

ofabel commented Aug 22, 2020

Since ncc uses webpack under the hood you can use the native node require function with __non_webpack_require__. So I implemented my own cache by extending from the TwingCacheFilesystem:

class Cache extends TwingCacheFilesystem {
    load(key) {
        let modulePath = path.resolve(key);
        const requireFunc = typeof __non_webpack_require__ === 'function' ? __non_webpack_require__ : require;
        return new Promise((resolve) => {
            fs.stat(modulePath, (err) => {
                if (err) {
                    resolve(() => new Map);
                }
                else {
                    let cache = requireFunc.cache;
                    delete cache[requireFunc.resolve(modulePath)];
                    resolve(requireFunc(modulePath));
                }
            });
        });
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants