init-package-json
init-package-json is a Node.js module designed to programmatically and interactively create or update `package.json` files, primarily used by the npm CLI itself. It provides a wizard-like experience for users, prompting for essential package metadata such as name, version, description, entry point, test command, git repository, keywords, author, and license. The current stable version is 8.2.5, with frequent maintenance releases addressing bug fixes and dependency updates, often tied to releases of other `@npmcli` packages. Its key differentiator is its integration with `promzard` for flexible, scriptable prompting and the ability to utilize custom initialization files, offering a powerful way to standardize `package.json` creation across projects or teams. It is a low-level utility most often consumed by package managers rather than directly by end-user applications.
Common errors
-
Error [ERR_REQUIRE_ESM]: require() of ES Module <path/to/module> not supported. Instead change the require of <path/to/module> to a dynamic import() which is available in all CommonJS modules.
cause Attempting to `import` `init-package-json` as an ES module in a CommonJS context, or vice-versa, when the package is primarily CommonJS.fixUse `const init = require('init-package-json')` for CommonJS projects. If in an ESM module, consider `await import('init-package-json')` if the package provides a compatible export, or wrap it in a CommonJS context. -
Error: The "init-package-json" package requires Node.js version ^20.17.0 || >=22.9.0.
cause Running the package with an unsupported Node.js version.fixUpgrade your Node.js environment to a version compatible with `^20.17.0` or `>=22.9.0`. -
Error: Cannot find module '<path/to/custom/initFile>'
cause The `initFile` path provided to the `init` function is incorrect, or the file does not exist.fixDouble-check the `initFile` path to ensure it is absolute and points to an existing JavaScript file that exports a `promzard` function.
Warnings
- breaking Version 8.0.0 introduced significant changes to Node.js compatibility requirements. The package now requires Node.js `^20.17.0 || >=22.9.0`.
- breaking In v8.0.0, a new `type` prompt was added during the interactive initialization process, and the sort order of fields in the created `package.json` file was changed.
- gotcha The `initFile` parameter expects a path to a `promzard` module, which is a JavaScript file exporting a function, not a simple JSON configuration file. This allows for dynamic and interactive prompting logic.
Install
-
npm install init-package-json -
yarn add init-package-json -
pnpm add init-package-json
Imports
- init
import init from 'init-package-json'
const init = require('init-package-json') - init
const init = require('init-package-json') - PromZardContext
/* PromZard context is implicitly passed. See PromZard documentation. */
Quickstart
const init = require('init-package-json');
const path = require('path');
const fs = require('fs/promises');
async function initializePackage() {
// Define a temporary custom init file for demonstration purposes
const tempInitFileContent = `
module.exports = function (data, cb) {
data.name = this.basename;
data.version = '1.0.0';
data.description = 'A new package initialized via init-package-json!';
data.main = 'index.js';
data.scripts = { test: 'echo \"Error: no test specified\" && exit 1' };
data.license = 'ISC';
data.author = this.config.author || '';
cb(null, data);
};
`;
const customInitFilePath = path.join(__dirname, '.npm-init-custom.js');
await fs.writeFile(customInitFilePath, tempInitFileContent);
const targetDir = path.join(__dirname, 'my-new-package');
await fs.mkdir(targetDir, { recursive: true });
const configData = { author: 'My Name <me@example.com>' };
try {
console.log(`Initializing package.json in ${targetDir}...`);
const resultData = await init(targetDir, customInitFilePath, configData);
console.log('package.json initialized successfully:');
console.log(JSON.stringify(resultData, null, 2));
} catch (error) {
console.error('Failed to initialize package.json:', error);
} finally {
// Clean up the temporary init file
await fs.unlink(customInitFilePath);
console.log('Cleaned up temporary init file.');
}
}
initializePackage();