I would like to know if there is a way in NodeJs to get the name property from my project package.json
file:
{
"name": "bendiciones",
"version": "1.12.0",
"description": " bendiciones",
"main": "main.js",
"scripts": {
...
}
I've tried with
import {name} from './package.json';
import {name} from './app.json'
but I got the errors:
TS2307: Cannot find module './package.json'.
TS2307: Cannot find module './app.json'.
I've tried also with:
console.log ('--2>', process.env.npm_package_name);
but I get undefined
I had a similar issue. As a solution, you should add a custom typing ie json-loader.d.ts
with the content
declare module "*.json" {
const value: any;
export default value;
}
If you're using TypeScript, this becomes easy:
import pkg from '../path/to/package.json';
pkg.name;
It does require the following compilerOptions
in your tsconfig.json
:
{
"compilerOptions": {
"module": "commonjs",
"resolveJsonModule": true,
"esModuleInterop": true
}
}
You can require
the entire file and choose whichever properties you want:
const packageJSON = require("path/to/your/package.json");
console.log(packageJSON.name);
I also want to do the same and here's the code that worked. Since it uses require
to load the package.json
, it works regardless of the current working directory.
var packageFile = require('./package.json');
console.log(packageFile);
A warning:
Be careful not to expose your
package.json
to the client, as it means that all your dependency version numbers, build and test commands and more are sent to the client.
If you're building server and client in the same project, you expose your server-side version numbers too. Such specific data can be used by an attacker to better fit the attack on your server.
If you are using pure Javascript with no loaders you will have to load the package.json file manually:
import { readFileSync } from "fs";
// ./package.json is relative to the current file
const packageJsonPath = require.resolve("./package.json");
const packageJsonContents = readFileSync(packageJsonPath).toString();
const packageJson = JSON.parse(packageJsonContents);
console.log(packageJson.name);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.