0

I would like to know what methods are available to specify which modules should my app import based on a target platform. I would like to import different implementations for the same interface in typescript for a browser and for a nodejs.

We have something like

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

In c++

How could i achieve something similar using typescript node and browserify?

Playdome.io
  • 3,137
  • 2
  • 17
  • 34
  • Possibly without writing if statements in the code and avoiding the node implementation to be exposed in the browserify bundle. – Playdome.io Jun 04 '17 at 10:57

2 Answers2

1

which modules should my app import based on a target platform

Use the browser property in package.json.

More

Recommend creating a node implementation as default and point types to the definitions generated from that. More on types : https://egghead.io/lessons/typescript-create-high-quality-npm-packages-using-typescript

basarat
  • 261,912
  • 58
  • 460
  • 511
0

In nodejs, you can do it the following way, as per this post: 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]);

In the browser, you can check the os through the navigator object:

// 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()]);
Mμ.
  • 8,382
  • 3
  • 26
  • 36