编辑:添加插件配置更清晰
我正在使用 uuid
打包在一个汇总项目中。起初我收到外部依赖的警告 加密 .所以我加了external
和 output.globals
在我的汇总配置中:
export default [{
input: '/path/to/input.js',
external: ['crypto'],
output: {
file: '/path/to/output.esm.js',
format: 'esm',
...
globals: {
crypto: 'crypto'
}
},
plugins: [
resolve({
customResolveOptions: {
moduleDirectory: 'node_modules'
},
preferBuiltins: true
}),
commonjs({
namedExports: {
uuid: ['v4']
}
})
]
}];
警告消失了,但现在我的输出文件中有一个导入语句:
输出.esm.js
import crypto from 'crypto';
...
我的问题是,如果我包含
output.esm.js
,这会起作用吗?在浏览器中?<script type="module" src="/path/to/output.esm.js"></script>
最佳答案
At first I was getting a warning for external dependency crypto
这是因为 Rollup 不知道是否要使用 node 内置的
crypto
或外部包装。 @rollup/plugin-node-resolve
的preferBuiltins
用于在这些备选方案之一之间进行选择。So I added external and output.globals in my rollup configuration
这些选项连同
preferBuiltins: true
告诉 Rollup 使用节点的内置 crypto
没有捆绑它(因此导入语句仍然存在于输出文件中)。但是,如果您的目标环境是浏览器,您应该使用 browser alternative由
uuid
提供依赖于 Web Crypto API 而不是节点的 crypto
.为此,以下汇总配置就足够了:// rollup.config.js
export default [{
input: ...,
output: {
file: ...,
format: 'esm',
},
plugins: [
resolve({
browser: true, // This instructs the plugin to use
// the "browser" property in package.json
}),
commonjs(),
],
}];
只是出于好奇:
My question is will this work if I include output.esm.js in browser?
<script type="module" src="/path/to/output.esm.js"></script>
不,它不会;主要是因为浏览器不理解裸模块说明符(
import crypto from 'crypto'
而不是 './path/to/crypto.js'
)。此外,根据您的汇总配置 crypto
被视为 nodejs 内置,除非捆绑,否则在浏览器中不可用:)
关于dependencies - 在汇总 ESM 库中导入 uuid 会在输出文件中为 "crypto"创建导入语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59937658/