javascriptwebpackcross-platformbabeljsshim

Creating a cross platform javascript library


Im currently working on a library, which targets different javascript runtime environments (namely node, modern browsers). Therefore i have a npm project, with babel to write ES6 code, transpile it to run in node and execute tests.

Now i'm encountering situations where modules have to be written for different targetted platforms, e.g. i need to use the Web Audio Api (which is not supported in node) to generate some sounds. My idea is to create a module (e.g. sound.js) which provides a uniform interface, no matter for which targeted platform, but has dependencies corresponding to the runtime environment. In addition, with different dependencies i have to provide different implementations inside sound.js, this is called shimming (or adapter pattern) as i understand it. The figure below illustrates my idea on how this process works:

-- src
  -- modules
    -- sound.js
       ...
  -- node_modules
       -- webAudio
       -- nodeAudio

Inside sound.js

...
// if target == web
import * from 'webAudio'
// if target == node
import * from 'nodeAudio'
...
function playSound() {
    //if platform == 'node'
    nodeAudio.play()

    //if platform == 'browser'
    webAudio.play()
}

At this point, i'm simply overwhelemed by the world of cross platform developement in the JavaScript universe. From my understanding i would add webpack to babel and bundle different dist/ packages for every platform. But i dont find any ressources on how to approach the implementation of the sound.js shim. So...

Is this concept above a viable approach to build a crossplatform library and if not where can i find ressources concerning this sccenario ?


Solution

  • TL;DW I ended up using different methods mentioned in this fantastic blog post.

    Mainly browserify in order to shim dependencies and adding various grunt task for testing and linting.