While @stackoverflow221's answer is good, it adds the type
at the end of the package.json
, which feels slightly unnatural to me.
I prefer to put the type
right above the entry
, given they are closely related.
For that, I have the following bash function on my .bashrc
, but it should be easy to adapt to any shell configuration:
# custom 'npm init'
# - runs regular 'npm init', interactively
# - then, if successful, add "type": "module" to the generated package.json,
# - right above the line containing "main".
function npm-init () {
npm init
# if package.json was not created, exit (this means the user cancelled)
# (npm init has no error codes)
if [[ ! -f package.json ]]; then
return 1
fi
sed -i '/"main":/i\ "type": "module",' package.json
}
Then, just run npm-init
instead of npm init
npm init
process, as described in the docs. – Whalingtype
is not a standard field inpackage.json
. docs.npmjs.com/files/package.json – Hindwardyarn
, so just setting my own local preference will not work. Worst case scenario, I can read package.json, modify it, and write it back. The question is whether I can do this easily, in the shell, usingnpm
oryarn
, in a way that does not involve just readingpackage.json
and handling it myself. – Rodrigorodriguetype
field in 2019.. The question was not "Should I put atype
field in my package.json?" – Rodrigorodriguetype
field is currently experimental and who knows it may just be temporary - hence why npm hasn't formally listed as a "standard" field. Personally, I (like many others) don't use the experimental ESM syntax in production code. – Whaling--experimental_modules
flag and process ES6 modules. Like I said, it is not a concern. – Rodrigorodrigue