How to configure package.json for a JavaScript project
· Category: JavaScript
Short answer
package.json defines project metadata, dependencies, scripts, and configuration. Key fields include name, version, main, type, scripts, and dependencies.
Steps
- Initialize a project:
bash npm init -y - Define scripts:
json { "scripts": { "start": "node src/index.js", "build": "webpack --mode=production", "test": "jest" } } - Set the module type:
json { "type": "module" } - Specify entry points:
json { "main": "dist/index.cjs", "module": "dist/index.mjs" }
Tips
- Use
enginesto specify supported Node.js versions. - Use
filesto whitelist what gets published to npm.
Common issues
- Forgetting to set
type: modulewhen using ES modules causes syntax errors. - Misconfigured
mainfields lead to consumers importing the wrong file.