问题
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
export
must be at the top level of the file, which means you can't use the syntax from the ES5 answerexport
isn't a function (is it?), so you can't usetype 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