26

I've authored a javascript library using Webpack. The entrypoint someClass.js looks like this:

import x from './x'
/* several more imports here */

class SomeClass {}

export default SomeClass;

My webpack config that bundles this library is as follows:

module.exports = {
    entry: './someClass.js',
    output: {
        path: __dirname,
        filename: 'lib.js',
        library: 'lib',
        libraryTarget: 'umd',
    },

I then import the generated lib.js into a simple index.html that is defined as follows:

<!DOCTYPE html>
<html>
<head>
</head>

<body>
<script src="app.js" type="module"></script>
</body>
</html>

In app.js, I simply try to import the file as follows:

import  * as lib from './lib.js';

console.log(lib);

// Output: Module {Symbol(Symbol.toStringTag): "Module"}   Symbol(Symbol.toStringTag): "Module"

However, this import statement does not seem to work as planned (I expect a module with a default field that is my SomeClass constructor).

The only way I can access my library's default export SomeClass is if I do a global import statement in app.js as follows, which sets lib as an object on window:

import './lib.js';
console.log(window.lib);

// Output: Module {default: ƒ, __esModule: true, Symbol(Symbol.toStringTag): "Module"} default: class SomeClass_SomeClass

I don't want my class to available at the global window, as it makes it tough to modularise my code.

I also want to be able to use this library in a variety of places on the web (react app, standalone html files, etc), and so want to minimize dependencies.

Is there anything I can do to import the module as an es6 import?

StillFiles2
  • 371
  • 3
  • 4

2 Answers2

0

The ES6 import works only with the export keyword like:

export { A }
export default B

Nodejs's commonjs2 module will not work on the Web, which looks like:

module.exports = { A, default: B }

Webpack's libraryTarget: "umd" output will not keep the ES6 export keyword either, for reason that the keyword syntax is not ployfill-able and will break on other environment.

So you may want to release with 2 set of files like other packages do (cjs/ and es/), and use babel or rollup to pack the es/ version and keep the ES6 export keyword.

Also check out: Output an ES module using webpack which explains the Webpack part really well.

dr-js
  • 36
  • 4
0

There is one default class exported:

import SomeClass from './lib' therefore should work?

Otherwise we should check the webpack bundle to find out what's happening. I don't think there is a use case for * as at all.


ECMAScript is supported since Node.js 13.2.0. So I vote for transpiling to es6 & upgrade Node.js if ancient.


‍ Since async & defer it's recomomend again to put <script> into <head>.

faebster
  • 727
  • 7
  • 13