有没有办法“npm init”ES模块?

问题描述 投票:0回答:5

所有现代版本的 Node 都需要运行包,因为模块是

"type": "module"
中的
package.json
,但我没有看到任何用于
npm init
yarn init
的标志来添加该属性。

是否有一个包管理器的标志,可以将值添加到

package.json
(即
npm package-property set type module
或类似的东西)?

javascript node.js npm yarnpkg es6-modules
5个回答
9
投票

这正是您所要求的:

npm init es6

它会创建一个带有

package.json
设置的
"type": "module"

来源:https://www.npmjs.com/package/create-es6


6
投票

不久前看到这个问题,最长的时间我使用“npm init esnext”。我刚刚弄清楚如何直接从命令行编辑 package.json 键:

npm init -y; npm pkg set type="module";

虽然第一个命令会将不带

package.json
"type": "module"
的内容记录到控制台,但如果您打开
package.json
,您将看到它已被第二个命令正确添加。


0
投票

虽然@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


-1
投票

对于 ES 兼容模块,存在

create-esm
包。除此之外(docs)它还填充模块字段。

看来你可以使用

npm init esm


-1
投票

运行时可以设置默认值

pnpm init

npm config set init.type module
© www.soinside.com 2019 - 2024. All rights reserved.