首页 > 解决方案 > 使用带有汇总的旧 Require 模块

问题描述

我认为 commonjs 插件可以让您使用较旧的模块,但我无法汇总使用https://www.npmjs.com/package/create-hmac。据我所知,这是一个较旧的模块,我需要使用:

const createHmac = require("create-hmac");

我不能使用导入。有什么办法可以将它与汇总一起使用,还是我不走运?我正在使用标准的 Svelte 汇总模板,并尝试使用 namedExports、dynamicRequireTargets、不同的 Resolve 设置等。如果任何真正了解汇总的人可以帮助我,将不胜感激!

标签: hmacsvelterollupjs

解决方案


你可以import实际使用,这就是@rollup/plugin-commonjs它的用途。它允许您import使用导出的模块require

import createHmac from 'create-hmac'

但这就是这个模块所做的一切。对你来说还不够。汇总不会自行解决node_modules等。这不是标准的 ES 模块分辨率,它是特定于节点的分辨率。因此,为此,您还需要@rollup/plugin-node-resolve.

还是不够。我试过这个create-hmac包。它需要 Node 环境中存在但浏览器中不存在的东西(例如流……)。据我所知,Webpack 会自动对其进行 polyfill,但 Rollup 不会。所以你还需要一个插件。我试过了rollup-plugin-node-builtins。似乎工作。

因此,最后,您的汇总配置应如下所示:

import resolve from '@rollup/plugin-node-resolve'
import commonjs from '@rollup/plugin-commonjs'
import builtins from 'rollup-plugin-node-builtins'

export default {
  // ...
  plugins: [
    // polyfills Node builtins in the browser
    builtins(),

    // Node resolution mechanism (node_modules)
    resolve({
      // this tells to use the 'browser' field of the packages you install
      // when they provide it (the package you've linked does)
      browser: true,
    }),

    // to allow import of module using require
    commonjs(),
  ]
}

推荐阅读