首页 > 解决方案 > 汇总后 crypto.createHmac 未定义

问题描述

我正在尝试将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 上的相关export声明node/crypto.js显示正在导出 createHmac。

节点/crypto.js L147

更新 1(解决方案?)

似乎删除该importsecurity.js可以解决问题。我知道这crypto是一个内置的节点模块。

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

标签: node.jsecmascript-6rollupjs

解决方案


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

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

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

使用时设置crypto为。它默认为. 那不是我想要或不需要的。falsebuiltins()commonjsbrowserify

// 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.


推荐阅读