2017-10-19 94 views
3

我有一個客戶端應用程序,它使用一些瀏覽器全局屬性,如Elementdocument定義綁定到umd或commonjs時的全局變量

我想我的運行在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'); 

我目前使用的彙總捆綁不同版本my-app,我怎麼能彙總做這個對我來說_servermy-app版本自動my-app的消費者不必這樣做?

我正在考慮編寫自己的彙總插件,但我覺得重寫全局變量似乎是一種常見的做法。

回答

2

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的主要文件中的下列意味着服務器捆綁,類似的做法如何反應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並且僅爲服務器條目定義SERVER_ONLYhttps://github.com/rollup/rollup-plugin-replace#usage)。如果您使用UglifyJS或消除死代碼的相似工具,則不會有domino和重複的服務器代碼。

編輯:注意到一個小問題。條件應該是if (SERVER_ONLY) {。對服務器入口文件使用以下定義。

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

謝謝!這是我正在尋找的 - 但當我這樣做時,我的主要文件捆綁看起來是這樣的: '(function(global,factory){ \t typeof exports ==='object'&& typeof module! =='undefined'?factory(): \t typeof define ==='function'&& define.amd?define(factory): \t(factory()); }(this,(function(){'use嚴格的 '; module.exports =需要(' ./服務器 '); })));' –

+0

這是一個UMD模塊......注意單「需要(' ./服務器')「,這就是它,它沒有解決要求。 –

+0

我已經更新了我的答案 –