GithubHelp home page GithubHelp logo

import-fresh's Introduction

import-fresh

Import a module while bypassing the cache

Useful for testing purposes when you need to freshly import a module.

ESM

For ESM, you can use this snippet:

const importFresh = moduleName => import(`${moduleName}?${Date.now()}`);

const {default: foo} = await importFresh('foo');

This snippet causes a memory leak, so only use it for short-lived tests.

Install

$ npm install import-fresh

Usage

// foo.js
let i = 0;
module.exports = () => ++i;
const importFresh = require('import-fresh');

require('./foo')();
//=> 1

require('./foo')();
//=> 2

importFresh('./foo')();
//=> 1

importFresh('./foo')();
//=> 1

Related

import-fresh's People

Contributors

adammockor avatar azatoth avatar coreyfarrell avatar julienkode avatar ronami avatar sindresorhus avatar stroncium avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

import-fresh's Issues

Throws an error if called from module without parent / which only called itself

I have the situation where after bundling with Rollup I get an error when trying to resolve a config file through cosmiconfig and traced the error back to this package.

In my situation, after bundling, the bundled file is the top level module and import-fresh and the packages it depends on are also in that same file. The call to parent-module then returns undefined because the call stack only consists of the file itself. The next call to resolve-from on the other hand expects the filePath to be a string and throws. I think falling back to the moduleId-path or __filename should be done instead.

I can reproduce this if I place the code of import-fresh in the same file and invoke it like this:

const path = require('path');
const resolveFrom = require('resolve-from');
const parentModule = require('parent-module');

// code of import-fresh ...

function a() {
    b();
}
function b() {
    c();
}
// repeat until....
function h() {
   importFresh('./doesnt-matter');
}
a();

Reproduced on Windows 10 with node v14.5.0

I'm still not sure if I'm doing something wrong elsewhere because your package is used by so many other packages and noone has opened this issue yet.

ES2015/Babel conflict when using import-fresh inside functions

When using Gulp 4 and Babel, placing import-fresh inside a function causes a TypeError. The odd thing is this doesn't happen if the import-fresh call happens at root:

// Works as expected:
var works = importFresh(path.resolve('./src/stuff'))

function something() {
    // Errors out:
    var worksNot = importFresh(path.resolve('./src/otherStuff'))
}

The error:

TypeError: Cannot read property 'getFileName' of undefined
    at module.exports (/(...)/node_modules/caller-path/index.js:4:40)
    at module.exports.moduleId (/(...)/node_modules/import-fresh/index.js:11:44)
    at imported (/(...)/gulpfile.babel.js:14:14)
    at /(...)/gulpfile.babel.js:28:2
    at taskWrapper (/(...)/node_modules/undertaker/lib/set-task.js:13:15)
    at bound (domain.js:301:14)
    at runBound (domain.js:314:12)
    at asyncRunner (/(...)/node_modules/async-done/index.js:55:18)
    at _combinedTickCallback (internal/process/next_tick.js:131:7)
    at process._tickCallback (internal/process/next_tick.js:180:9)

When the same script runs without Babel, it works as expected. So there's something weird happening with Babel / ES2015 conversion.

Critical dependency warning when bundling with Webpack 5

I've ran into an issue when trying to run a React application with Webpack 5. I receive the warning

WARNING in ../../../.yarn/cache/import-fresh-npm-3.3.0-3e34265ca9-2cacfad06e.zip/node_modules/import-fresh/index.js 32:31-48

Critical dependency: the request of a dependency is an expression

According to here this is caused by something like:

let var1 = someCall();
require(var1); // webpack can't determine var1 value

Here is the location in your source code which could be the problem.

https://github.com/sindresorhus/import-fresh/blob/main/index.js#L32 report there. ( not sure that this should work with webpack )

Node 16 Memory leak

We are currently using (and loving) this package over our current production applications while we using Node14.

As part of our tech upgrades, we are moving towards Node16 and while we tested our codebase with the new node version, we discovered while monitoring to pods that we huge memo leak.

I tried reproducing the issue using the heapdump script of this package and I got this following results:

-- Node 14 --

  • require

image

  • importFresh

image

-- Node 16 --

  • require

image

  • importFresh

image

It seems that there is a notable difference between two, I might have missed something tho has anybody else had experienced that?

Appreciated, cheers πŸŽ‰

Not working with Jest

When running unit tests with Jest, the importFresh function does not work properly, it always returns the same (cached?) module.

Might be due to the fact that Jest patch require with its own implementation :/

Browserify support

Does not work with browserify. Underlying issue is here sindresorhus/resolve-from#10

Some context on how that gets called:

resolveFrom is called with these values

resolveFrom(path.dirname(callerPath()), moduleId)
resolveFrom(path.dirname(undefined), moduleId)
resolveFrom(".", "./foo")

resolveFileName is called with these values

const resolveFileName = () => Module._resolveFilename(moduleId, {
  id: fromFile,
  filename: fromFile,
  paths: Module._nodeModulePaths(fromDir)
});
const resolveFileName = () => Module._resolveFilename("./foo", {
  id: "/http:/localhost:9966/noop.js",
  filename: "/http:/localhost:9966/noop.js",
  paths: Module._nodeModulePaths("/http:/localhost:9966")
});

Transparent module.parent

Issuehunt badges

module.parent in module required by requireUncached will be the [...]/require-uncached/index.js module.

Can we please fix it to be the parent of that? Meaning, the module.parent.parent? I think it makes sense.


IssueHunt Summary

stroncium stroncium has been rewarded.

Backers (Total: $80.00)

Submitted pull Requests


Tips


IssueHunt has been backed by the following sponsors. Become a sponsor

Memory leak

This module creates memory leak. Simple test case scenario is:

const heapdump = require('heapdump');
const requireUncached = require('require-uncached');

let i, m1, m2;

for (i = 0; i < 100000; i++) {
  m1 = require('./module.js');
  m1();
}

heapdump.writeSnapshot('./before-' + Date.now() + '.heapsnapshot');

for (i=0; i < 100000; i++) {
  m2 = requireUncached('./module.js');
  m2();
}

heapdump.writeSnapshot('./after-' + Date.now() + '.heapsnapshot');

More information can be found here nodejs/node#8443.

I can PR this, but I am not sure how to handle this correctly.

Atom Deprecation Cop warning - Argument to path.dirname must be a string

Atom Deprecation Cop warning:

Deprecated calls
atom core (1 deprecation)
Argument to path.dirname must be a string

Object.dirname - /usr/share/atom/resources/app.asar/src/electron-shims.js:9:10
module.exports.moduleId - /home/jk/.atom/packages/atom-standard-formatter/node_modules/import-fresh/index.js:11:36
loadJSConfigFile - /home/jk/.atom/packages/atom-standard-formatter/node_modules/standard/node_modules/eslint/lib/cli-engine/config-array-factory.js:189:16
loadConfigFile - /home/jk/.atom/packages/atom-standard-formatter/node_modules/standard/node_modules/eslint/lib/cli-engine/config-array-factory.js:251:20
ConfigArrayFactory._loadConfigData - /home/jk/.atom/packages/atom-standard-formatter/node_modules/standard/node_modules/eslint/lib/cli-engine/config-array-factory.js:415:13
ConfigArrayFactory._loadExtendedShareableConfig - /home/jk/.atom/packages/atom-standard-formatter/node_modules/standard/node_modules/eslint/lib/cli-engine/config-array-factory.js:718:21
'use strict';
const path = require('path');
const resolveFrom = require('resolve-from');
const parentModule = require('parent-module');

module.exports = moduleId => {
	if (typeof moduleId !== 'string') {
		throw new TypeError('Expected a string');
	}

	const filePath = resolveFrom(path.dirname(parentModule(__filename)), moduleId);

	// Delete itself from module parent
	if (require.cache[filePath] && require.cache[filePath].parent) {
		let i = require.cache[filePath].parent.children.length;

		while (i--) {
			if (require.cache[filePath].parent.children[i].id === filePath) {
				require.cache[filePath].parent.children.splice(i, 1);
			}
		}
	}

	// Delete module from cache
	delete require.cache[filePath];

	// Return fresh module
	return require(filePath);
};

Fails with "Path must be a string" on Node 8

In certain conditions import-fresh fails with the error message Path must be a string. Received null on Node 8.

importFresh('global-dirs');
 Path must be a string. Received null
  module.exports.moduleId (~/node_modules/import-fresh/index.js:11:36)
  ...

Example build: travis/commitlint#L1738

Digging deeper reveals this is caused by caller-path returning a Callsite that returns null from its getFileName method: caller-path/index.js#L4

This in turn is caused by caller-callsite returning always the very first Callsite it finds by breaking out of the iteration here: caller-callsite/index.js#L13

Removing the break statement fixes the issue for me - I am not familiar with the APIs used here, so I am not very confident this is the appropriate fix though.

Steps to reproduce

n 8.9.1
git clone https://github.com/marionebl/commitlint.git
cd commitlint 
git checkout import-fresh-null-repro
npx lerna bootstrap
cd `@commitlint/core
npx ava src/library/resolve-extends.test.js

Update parent-module to 3.1.0 to support bun

There was a bug with callsites package in bun runtime, which is dependency of parent-module package. Callsites package received patch for this 4.1.0 and it is already updated in parent-module in version 3.1.0. Please update it, as it doesn`t contain any changes from last 3.0.0 version except callsites package update. If you want, I can create PR for that, just ask)

Problem bundling with webpack

Hi, I just stumbled over bundling import-fresh with webpack. Webpack will not ignore the dynamic require calls and so this package will fail after bundling.

See here for a detailed description of the issue and my workaround.

An easy fix would be to add the "magic comments" to your code:

return parent === undefined ? require(/* webpackIgnore: true */ filePath) : parent.require(/* webpackIgnore: true */ filePath);

Users that want to bundle your package with webpack would still have to activate "magic comments" for require in their webpack config, so maybe there is a better solution for this.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.