how to share javascript code between front- and back-end (ES6)

非 Y 不嫁゛ 提交于 2020-01-15 06:27:09

问题


This is an ES6-specific duplicate of this SO thread, which details how to create a javascript module that can be exported for use in both a browser and node context.

I would be just as glad for an answer to appear there, if that's more appropriate.

For background, here's a quote of the ES5 solution, as well as the problems that arise in trying to translate it to ES6. (Credit to users @caolan and @broesch.)

(function(exports){

    // Your code goes here. For example: 
   exports.test = function(){
        return 'hello world'
    };

})(typeof exports === 'undefined'? this.mymodule = {} : exports);

Thus, if exports is undefined, you must be in the browser, in which case mymodule is declared on the window (i.e., this). Or, if exports is defined, it's in a node context, in which case you can just var mymodule = require('mymodule'). And in either environment, you can then use it as mymodule.test(). Great.

One problem with this is that exports.whatever doesn't expose whatever in the current scope, so if you want to use whatever within the module, you end up needing to do

var whatever = 3;
exports.whatever = whatever;

which can get cumbersome, and is easy to forget.

In ES6, on the other hand, you can do export const whatever = 3, which would both export and expose whatever, which is DRYer and thus easier to maintain.

The new problems are that

  1. export must be at the top level of the file, which means you can't use the syntax from the ES5 answer
  2. export isn't a function (is it?), so you can't use type of to achieve the conditional browser/node context.

So, my question is: what is the ES6 version of creating a .js file that can exported to both the browser and node?

来源:https://stackoverflow.com/questions/59736730/how-to-share-javascript-code-between-front-and-back-end-es6

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!