-
Notifications
You must be signed in to change notification settings - Fork 30.5k
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
Proposal: Built-in __VERSION__ Import for Package Version Detection #56828
Comments
Something like this would have to work for both CJS and ESM, and would have to be something the package couldn’t export itself - and what would happen if you tried to import this from something that wasn’t a package specifier? Reading package.json manually seems like a pretty good approach to me, and #55412 seems like it helps with that. |
I think adding Why
|
Instead of modifying the module system to inject Since Seems like a much cleaner and more flexible solution. Thoughts? |
How it could work internallySomething like this: import { readFileSync } from 'fs';
import { dirname, join } from 'path';
import { createRequire } from 'module';
const require = createRequire(import.meta.url);
function getPackageVersion(packageName) {
try {
const packagePath = require.resolve(packageName);
const packageDir = dirname(packagePath.split(`${packageName}/`)[0] + packageName);
const packageJson = JSON.parse(readFileSync(join(packageDir, 'package.json'), 'utf8'));
return packageJson.version || null;
} catch (err) {
return null;
}
} |
nit: You should be using |
What is the problem this feature will solve?
Many packages need to adapt their behavior based on the installed version of a dependency. Currently, there is no built-in way in Node.js to dynamically determine the version of an imported package at runtime. Developers must resort to workarounds such as reading package.json manually, which is cumbersome and inefficient.
For example, the nest-pino package supports both NestJS 10 and 11. However, NestJS 10 uses Express 4, while NestJS 11 uses Express 5. Because of this, a small change is required:
Should be:
p.s. I'm not affiliated with that package
What is the feature you are proposing to solve the problem?
A convenient way to read the version from
package.json
. Something like:This way, 'nest-pino` can adapt to both version by using:
The beautiful thing is that this will require zero efforts from package maintainers.
If a package already exports a
__VERSION__
variable, then that takes precedence over the one supplied by node.What alternatives have you considered?
pkginfo
, but why add another package for something that node can easily provide?The text was updated successfully, but these errors were encountered: