dependencies - 在汇总 ESM 库中导入 uuid 会在输出文件中为 "crypto"创建导入语句

标签 dependencies uuid guid cryptojs rollup

编辑:添加插件配置更清晰

我正在使用 uuid打包在一个汇总项目中。起初我收到外部依赖的警告 加密 .所以我加了externaloutput.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-resolvepreferBuiltins用于在这些备选方案之一之间进行选择。

So I added external and output.globals in my rollup configuration


这些选项连同 preferBuiltins: true告诉 Rollup 使用节点的内置 crypto没有捆绑它(因此导入语句仍然存在于输出文件中)。
但是,如果您的目标环境是浏览器,您应该使用 browser alternativeuuid 提供依赖于 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/

相关文章:

mysql - 存储 MySQL GUID/UUID

c# - 在不使用字符串的情况下将 ExecuteScalar 结果转换为 GUID?

algorithm - 机器生成的 UUID 只能产生零吗?

range - 如何在 cassandra 中使用 timeuuid 名称

batch-file - 使用批处理文件在 Windows 中生成 GUID

java - Maven 在本地存储库中找到 Artifact 但无法编译

java 7 uuid 错误?

maven - 父项中的 dependencyManagement 被忽略

python循环导入和访问类

PHP Order数组基于元素依赖