【问题标题】:Node / Javascript import different modules based on target platform?Node / Javascript根据目标平台导入不同的模块?
【发布时间】:2017-06-04 10:56:17
【问题描述】:

我想知道有哪些方法可用于指定我的应用应基于目标平台导入哪些模块。我想在 typescript 中为浏览器和 nodejs 导入相同接口的不同实现。

我们有类似的东西

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

在 C++ 中

如何使用 typescript node 和 browserify 实现类似的功能?

【问题讨论】:

  • 可能无需在代码中编写 if 语句并避免在 browserify 包中暴露节点实现。

标签: javascript node.js typescript browserify


【解决方案1】:

我的应用应根据目标平台导入哪些模块

使用package.json 中的browser 属性。

更多

建议创建一个node 实现作为默认实现,并将types 指向由此生成的定义。更多关于类型:https://egghead.io/lessons/typescript-create-high-quality-npm-packages-using-typescript

【讨论】:

    【解决方案2】:

    在 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()]);

    【讨论】:

    • “可能不用在代码中写 if 语句”,因为我使用的是打字稿。
    • nodejs 中的浏览器和 nodejs 我有共享的代码库,我应该包含和使用不同的库。
    • 查看我的更新答案,包括浏览器和 nodejs
    猜你喜欢
    • 2021-04-08
    • 1970-01-01
    • 1970-01-01
    • 2015-09-13
    • 1970-01-01
    • 1970-01-01
    • 2020-10-26
    • 2016-06-28
    相关资源
    最近更新 更多