简体   繁体   English

将ES6类从节点打包到浏览器

[英]Package an ES6 class from node to browser

I have been trying to package a super simple ES6 style class object to the browser. 我一直在尝试将超简单的ES6样式类对象打包到浏览器中。 Example

class Foo {
   constructor(){
        this.name = "Foo";
   }
}
module.exports = Foo;

Sure I can use this in my node projects just fine, but it's also a useful object for the browser. 当然,我可以在节点项目中使用它,但是它对于浏览器也是有用的对象。 So far I have tried webpack and browserify, but they do not expose the object globally. 到目前为止,我已经尝试过webpack和browserify,但是它们并未全局公开对象。 I was hoping to basically include the generated script file and be able to call let foo = new Foo() from the browser. 我希望基本上包括生成的脚本文件,并能够从浏览器中调用let foo = new Foo() How can I do this? 我怎样才能做到这一点?

*note that literally the only thing stopping me from just including the file in the browser directly is the module.exports *请注意,实际上阻止我仅将文件直接包含在浏览器中的唯一事情是module.exports

For Javascript 6 you wanna do something like: 对于Javascript 6,您想要执行以下操作:

class Foo {
   constructor(){
        this.name = "Foo";
   }
}
export default Foo;

(use export instead of module.exports) (使用export而不是module.exports)

Then from another js file do: 然后从另一个js文件执行:

import Foo from '<path_to_foo>';

For example, if Foo.js is in the same dir as the "other" module, then you can do: import Foo from './Foo'; 例如,如果Foo.js与“其他”模块位于同一目录中,则可以执行以下操作: import Foo from './Foo';

Then you can do let f = new Foo() 然后可以let f = new Foo()

Modern browsers tend to support js modules, however it is not guaranteed. 现代浏览器倾向于支持js模块,但是不能保证。

Hope this helps 希望这可以帮助

Without hacking a huge library, or building another node module to somehow automate this, I thought of that famous razor today and just did this. 无需破解庞大的库,也无需构建另一个节点模块以某种方式使它自动化,我今天想到了那把著名的剃刀,就这样做了。

if(typeof module !== "undefined"){
    module.exports = Foo;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM