Webpack Javascript Library - How to import Class directly?

118 Views Asked by At

I made new Javascript library with Webpack. I want to import class from this library directly. However, I need to put '.default' to run MyClass. I don't want to use '.default'. I just want to use MyClass directly. What should I do to solve it?

//index.js
export default class Myclass {
//...}
//webpack.config.js
output: {
   library: 'MyClass',
   libraryTarget: 'umd',
   libraryExport : "default",
   filename: 'index.js',
   path: path.resolve(__dirname, 'dist'),
},

Thanks for your help.

1

There are 1 best solutions below

0
JAE L On

I found the solution and I want to share it.

First, you have to set webpack.config.js like this.

//webpack.config.js
output: {
   library: 'MyClass',
   libraryTarget: 'umd',
   libraryExport : "default",
   filename: 'index.js',
   path: path.resolve(__dirname, 'dist'),
}

When you just import MyClass from other javascript projects, you could call MyClass without '.default'.

import MyClass from 'MyLibary';
const newInstance = new MyClass();

However when you import MyClass dynamically, you have to set 'default'.

const { default: MyClass } = await import('MyLibrary');
const newInstance = new MyClass();

It's done!