Sac*_*ngh 4 uuid dependencies guid rollup cryptojs
编辑:添加插件配置更清晰
我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']
}
})
]
}];
Run Code Online (Sandbox Code Playgroud)
警告消失了,但现在我的输出文件中有一个导入语句:
输出.esm.js
import crypto from 'crypto';
...
Run Code Online (Sandbox Code Playgroud)
我的问题是,如果我包含output.esm.js在浏览器中,这会起作用吗?
<script type="module" src="/path/to/output.esm.js"></script>
Run Code Online (Sandbox Code Playgroud)
起初我收到外部依赖加密的警告
这是因为 Rollup 不知道您是要使用 node 的内置crypto包还是外部包。@rollup/plugin-node-resolve'spreferBuiltins用于在这些选项之一之间进行选择。
所以我在汇总配置中添加了 external 和 output.globals
这些选项一起preferBuiltins: true告诉 Rollup 使用 node 的内置crypto而不捆绑它(因此 import 语句仍然存在于输出文件中)。
但是,如果你的目标环境是浏览器,你应该使用浏览器的替代提供uuid依赖于网络加密API,而不是节点crypto。为此,以下 Rollup 配置应该足够了:
// 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(),
],
}];
Run Code Online (Sandbox Code Playgroud)
只是出于好奇:
我的问题是,如果我在浏览器中包含 output.esm.js 这会起作用吗?
<script type="module" src="/path/to/output.esm.js"></script>
不,不会;主要是因为浏览器不理解裸模块说明符(import crypto from 'crypto'而不是'./path/to/crypto.js')。此外,根据您的 Rollup 配置crypto被视为内置的 nodejs,除非捆绑,否则在浏览器中不可用:)