How to publish ES6 classes with webpack 5 in bundle.js and import them in some using code?

619 views Asked by At

I have a React project where I created several ES6 classes. I would like to be able to use the generated bundle.js as a library, so that I am able to reuse the included ES6 classes.

Lets assume that my main file index.jsx contains following code:

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';

ReactDOM.render(<App />, document.getElementById('root'));

export default class Index {
  constructor() {
    this.foo = 'foo';
  }
}

and that Index is a class I would like to reuse.

I process the code with webpack and publish it as bundle.js file.

Then I would like to be able to reuse the code with something like:

A. ES6 imports

import Index from '../path/to/bundle.js';

or

B. Script tag in combination with requirejs

var bundleScript = document.createElement('script');
bundleScript.setAttribute('src','./path/to/bundle.js');
bundleScript.addEventListener('load', ()=> {
    console.log('loaded');
       
    require(['bundle'],(bundle)=>{
        console.log(bundle);        
    }, (error)=>{
        console.log(error);
    })
});

I tried several webpack configurations but did not get it working.

For A I get following error message:

Uncaught SyntaxError: The requested module
'../path/to/bundle.js' does not provide an export named 'default'

=> How can I define the default export of bundle.js?

It seems that defining some default export in my main file index.jsx does not work. My expectation would be, that I do not need to explicitly define the exports to publish. I would expect that all classes that I defined in their files with "default export class Foo {}" would be available.

For B I get some Module object for the required bundle:

enter image description here

However, I don't know how I can use that Module object. It does not have a property "Index" or "default" or whatever.


==> What is the right combination of webpack config and import method to get this working?

Example webpack output options:

output: {    
    filename: 'bundle.js',
    library: 'bundle',
    libraryTarget: 'umd',
...

Related questions:

Output an ES module using webpack

https://github.com/webpack/webpack/issues/3929

1

There are 1 answers

0
Stefan On

For the export of a single class following combination worked for me:

webpack output options:

filename: 'bundle.js',
library: 'bundle',
libraryExport: 'default' ,
libraryTarget: 'var',

usage:

import  '../path/to/bundle.js';

var instanceOfIndexClass = new window.bundle();