node.js - 汇总后 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。
更新 1(解决方案?)
似乎删除该import
行security.js
可以解决问题。我知道这crypto
是一个内置的节点模块。
我想了解为什么我不应该import
在这种情况下,而文档中的示例确实导入了模块。
解决方案
所以这是我想出的解决方案,对我来说效果很好。
rollup-plugin-node-builtins
作为开发依赖项安装在您的项目中。并将其导入您的rollup.config.js
:
import builtins from 'rollup-plugin-node-builtins'
使用时设置crypto
为。它默认为. 那不是我想要或不需要的。false
builtins()
commonjs
browserify
// 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 编写的,我正在构建我的模块的三个版本cjs
:umd
和es
.
推荐阅读
- c++ - 灯光显示,但立方体没有出现
- android - 处理双击底部导航项以刷新片段的最佳方法是什么
- ruby-on-rails - 日期时间的 Ruby 求和持续时间
- javascript - Navigator.getUserMedia() 已弃用。如何更改为 MediaDevices.getUserMedia()
- kiosk-mode - 通过 Android Management API 的单一 webapp 信息亭模式
- c# - 在 C# 中获取属性的值
- networking - 反向端口转发以提供对 apt 服务器的访问
- python - AttributeError:模块'tensorflow'在jupyter笔记本中没有属性'get_default_graph'
- angular - 从 app.module 中的本地 json 文件读取 api url
- java - 通用优先级队列java实现