Exporting a class with Webpack and Babel not working

后端 未结 2 576
栀梦
栀梦 2020-12-31 12:00

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:

<         


        
相关标签:
2条回答
  • 2020-12-31 12:09

    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.

    0 讨论(0)
  • 2020-12-31 12:10

    Webpack has changed a lot, now you can get the same results as the Felix Kling answer but with webpack config. You should add the libraryExport key in the output config and set it to "default". That would set your main class as the root content of your library. Here are the docs.

    Your webpack config should be like this:

    module.exports = {
      entry: {
        pentagine: "./lib/pentagine.js",
        demos: ["./demos/helicopter_game/PlayState.js"]
      },
    
      output: {
        path: __dirname,
        filename: "./build/[name].js",
        libraryTarget: 'umd',
        libraryExport: 'default' //<-- New line
      },
    
      module: {
        loaders: [
          {
            test: /.js$/,
            loader: 'babel-loader',
            exclude: /node_modules/,
            query: {
              presets: ['es2015']
            }
          }
        ]
      }
    };
    
    0 讨论(0)
提交回复
热议问题