所有现代版本的 Node 都需要运行包,因为模块是
"type": "module"
中的 package.json
,但我没有看到任何用于 npm init
或 yarn init
的标志来添加该属性。
是否有一个包管理器或的标志,可以将值添加到
package.json
(即npm package-property set type module
或类似的东西)?
这正是您所要求的:
npm init es6
它会创建一个带有
package.json
设置的 "type": "module"
。
不久前看到这个问题,最长的时间我使用“npm init esnext”。我刚刚弄清楚如何直接从命令行编辑 package.json 键:
npm init -y; npm pkg set type="module";
虽然第一个命令会将不带
package.json
的 "type": "module"
的内容记录到控制台,但如果您打开 package.json
,您将看到它已被第二个命令正确添加。
虽然@stackoverflow221的答案很好,但它在
type
的末尾添加了package.json
,这对我来说有点不自然。
我更喜欢将
type
放在 entry
的正上方,因为它们密切相关。
为此,我的
.bashrc
上有以下 bash 函数,但它应该很容易适应任何 shell 配置:
# 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 && sed -i '/"main":/i\ "type": "module",' package.json
}
然后,只需运行
npm-init
而不是 npm init
运行时可以设置默认值
pnpm init
npm config set init.type module