crypto.createHmac 在汇总后未定义

crypto.createHmac is undefined after rollup

我正在尝试 rollup 我图书馆的代码到 dist 文件夹中。
现在我的内置 crypto 库有问题。

终端输出:

$ yarn run build
  ...
  lib/helpers/security.js
  createHmac is not exported by node_modules/rollup-plugin-node-builtins/src/es6/empty.js
  ...

汇总配置

...
plugins: [
  builtins(),
  resolve(),
  json(),
  babel({
    exclude: ['node_modules/**','**/*.json']
  })
]
...

源代码

我的源代码片段:

// lib/helpers/security.js
import * as crypto from 'crypto'
crypto.createHmac('sha256',nonce).update(text).digest('base64');

结果

来自汇总,捆绑js输出:

undefined('sha256', nonce).update(text).digest('base64');

Crypto.js源代码

作为参考,github 上 node/crypto.js 中的相关 export 语句显示正在导出 createHmac。

node/crypto.js L147

更新 1(解决方案?)

security.js 中删除 import 行似乎可以解决问题。我知道 crypto 是一个内置的节点模块。

我想了解为什么在这种情况下我不应该import而文档中的示例导入模块.

我会避免 babel 服务器端文件,它可以做到,但我宁愿不这样做。 因此,如果您使用 require() 而不是导入,您可能不会遇到错误(Node.js v8 中未内置导入):

var crypto = require("crypto");

所以这是我想出的解决方案,对我来说效果很好。

在您的项目中安装 rollup-plugin-node-builtins 作为开发依赖项。并将其导入您的 rollup.config.js

import builtins from 'rollup-plugin-node-builtins'

使用builtins()时将crypto设置为false。它默认为 browserifycommonjs 版本。那不是我想要或需要的。

// set crypto: false when using builtins()
...
builtins({crypto: false}),
...

确保将 crypto 添加到您的 external 选项:

// add `crypto` to the `external` option
// you probably already have 
// one or more libs defined in there
let external = ['crypto']

现在我可以在我的库中使用 crypto 而不会出现之前使用我构建的文件时出现的问题。

import { createHmac } from "crypto";

结果是一个 4KB 大小的模块,它依赖于几个外部依赖项,但没有将它们包含在构建文件中。

对于上下文:我的源代码是用 ES6 编写的,我正在构建我的模块的三个版本:cjsumdes