2017-06-04 84 views
0

我想知道哪些方法可用来指定我的应用根据目标平台导入哪些模块。我想为浏览器和nodejs的typescript中的同一个接口导入不同的实现。节点/ Javascript导入基于目标平台的不同模块?

我们有一些像

#ifdef windows 
#include "windowsimplementation.h" 
#endif 

在C++

我怎么能使用打字稿节点实现类似的东西browserify?

+0

可能无需编写代码中的语句,并避免将节点实现暴露在browserify包中。 – Azarus

回答

0

在的NodeJS,你可以做下面的方式,按照这个帖子:How do I determine the current operating system with Node.js

// in Nodejs 
 
// possible values for process.platform 'darwin', 'freebsd', 'linux', 'sunos' or 'win32' 
 
var moduleString = { 
 
    'win32': 'windows-node-module', 
 
    'darwin': 'darwin-node-module', 
 
    // ... and so on 
 
} 
 

 
var module = require(moduleString[process.platform]);

在浏览器中,您可以通过检查操作系统navigator对象:

// in Browser 
 
// possible values windows, mac, linux 
 
var moduleString = { 
 
    'win': 'windows-browser-module', 
 
    'mac': 'mac-browser-module', 
 
    'linux': 'linux-browser-module', 
 
} 
 

 
function getOS(){ 
 
    return navigator.appVersion.indexOf("Win") != -1 ? 'win' : 
 
    (navigator.appVersion.indexOf("Mac") != -1) ? 'mac' : 'linux'; 
 
} 
 

 
var module = require(moduleString[getOS()]);

+0

“可能没有写代码中的语句”,因为我使用的是打字稿。 – Azarus

+0

您定位了多少个平台? –

+0

nodejs中的浏览器和nodejs我有共享的代码库,我应该包含并使用不同的库。 – Azarus