绑定到 umd 或 commonjs 时定义全局变量

Define globals when bundling to umd or commonjs

我有一个客户端应用程序,它使用了一些浏览器全局属性,例如 Elementdocument

我也想 运行 我在 node.js 中的应用程序,目前我正在用我的服务器中的 domino dom implementation 覆盖那些全局变量,如下所示:

const domino = require("domino");

const domimpl = domino.createDOMImplementation();
const document = domimpl.createHTMLDocument();

Object.assign(global, Element: domino.impl.Element, document};

const myApp = require('my-app');

我目前正在使用 rollup 来捆绑不同版本的 my-app,如何让 rollup 自动为 my-app_server 版本执行此操作,以便 [= 的消费者13=] 不必那样做?

我正在考虑编写自己的汇总插件,但我觉得覆盖全局变量似乎是一种常见的做法。

TLDR;使用单独的条目文件而不是汇总插件。

只需添加以下内容而不是汇总插件

if (typeof window ==== "undefined") {
  const domino = require("domino");    
  const domimpl = domino.createDOMImplementation();
  const document = domimpl.createHTMLDocument();    
  Object.assign(global, Element: domino.impl.Element, document};
}

// my-app code

您可能担心 domino 输入客户端代码。要解决这个问题,请为服务器和客户端使用单独的包,将上面的模拟代码包装在一个单独的文件中,并在 my-app 的主文件中使用以下内容用于服务器包,这种方法类似于 React ships production and development bundles - conditional imports.

服务器主文件

require(‘./globals-mocking’);
// my-app client code

客户端主文件

// my-app client code only

包的主文件

if (SERVER_ONLY) {
  module.exports = require('./my-app-server.js'); 
} else { 
  module.exports = require('./my-app-client.js'); 
}

仅将汇总的 replace plugin and define SERVER_ONLY (https://github.com/rollup/rollup-plugin-replace#usage) 用于服务器条目。如果您使用 UglifyJS 或消除死代码的类似工具,您将不会有 domino 和重复的服务器代码。

编辑:注意到一个小问题。条件应为 if (SERVER_ONLY) {。对服务器条目文件使用以下定义。

  plugins: [
    replace({
      SERVER_ONLY: JSON.stringify(true)
    })
  ]