使用Webpack和Babel导出类不工作 [英] Exporting a class with Webpack and Babel not working

查看:414
本文介绍了使用Webpack和Babel导出类不工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



以前,我有以下架构生成一个ES5版本的库:

我有一个非常简单的Webpack和Babel设置, / p>

  module.exports.lib =(function(){
/ *这里的私人部分库* /

return {
... / *这里的图书馆的公共部分* /
}
})();

一切都正常工作,我甚至有一些ES6功能,如我的库中的箭头功能一切都奏效但是,我决定将我的方法改为ES6类,这样:

 导出默认类库{

}

现在,当我尝试做:

  var library = new Library(); 

我得到没有定义库。即使只是评估返回未定义。



所以我所做的是将使用库的文件转换为ES6 从'libraryfile.js'导入库的文件,然后再次工作。



但是,我真的像我的输出库,仍然可以像以前一样从常规ES5与< script> 标签可用。这是可能吗?



这是我的webpack配置文件:

 模块.exports = {
条目:{
pentagine:./lib/pentagine.js,
演示:[./demos/helicopter_game/PlayState.js]
},

输出:{
路径:__dirname,
文件名:./build/[name].js,
libraryTarget:'umd'
$,

模块:{
装载机:[
{
测试:/.js$/,
加载程序:'babel-loader' ,
exclude:/ node_modules /,
查询:{
预设:['es2015']
}
}
]
}
};


解决方案

默认导出存储在模块的默认值属性。如果您希望让用户无需知道您的库即可访问,您可以将您的webpack文件更改为

  module.exports = require('./ libraryfile')。 

另外,请确保您有库:'YourLibraryName'您的webpack配置根据webpack.github.io/docs/configuration.html#output-library。


I have a very simple setup with Webpack and Babel for a small library.

Before, I had the following architecture to generate a ES5 version of the library:

module.exports.lib = (function () {
    /* private part of library here */

    return {
        ... /* public part of library here */
    }
})();

Everything is working fine this way, and I even had some ES6 features such as arrow functions inside my library and everything worked. However, I decided to change my approach to a ES6 class, this way:

export default class Library {

}

And now, when I try to do:

var library = new Library();

I get that Library was not defined. Even just evaluating Library returns undefined.

So what I did was turn the file that uses the library into an ES6 file that does import Library from 'libraryfile.js' and it worked again.

However, I'd really like my output library to still be usable from regular ES5 with a <script> tag just like before. Is this possible?

Here's my webpack config file:

module.exports = {
  entry: {
    pentagine: "./lib/pentagine.js",
    demos: ["./demos/helicopter_game/PlayState.js"]
  },

  output: {
    path: __dirname,
    filename: "./build/[name].js",
    libraryTarget: 'umd'
  },

  module: {
    loaders: [
      {
        test: /.js$/,
        loader: 'babel-loader',
        exclude: /node_modules/,
        query: {
          presets: ['es2015']
        }
      }
    ]
  }
};

解决方案

Default exports are stored in the default property of the module. If you want to make your library accessible without users having to know that, you can change your webpack entry file to

module.exports = require('./libraryfile').default;

Also, make sure you have library: 'YourLibraryName' in your webpack config as per webpack.github.io/docs/configuration.html#output-library.

这篇关于使用Webpack和Babel导出类不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆