I'm using webpack to bundle up a framework for use by 3rd parties. This framework should expose multiple ES6 classes. Building in a modular fashion, I have written one class per file. What I want to do is build all these files together, and have them bundled up under a given "namespace". Example:
apples.js export class Apples {...}
oranges.js export class Oranges {...}
webpack.config.js:
module.exports = {
entry: ['./src/apples.js', './src/oranges.js'],
output: {
path: './dist',
filename: 'fruit.js',
library: 'Fruit',
libraryTarget: 'umd'
}
}
However, if I load up this library in the browser and type Fruit
into the console, I only see the Oranges object under Fruit. Only the last entry file is being exposed back out in the library. Surely enough, the webpack docs confirm this behavior:
If you pass an array: All modules are loaded upon startup. The last one is exported. http://webpack.github.io/docs/configuration.html#entry
My current workaround is to export all my classes from one file, but it's getting pretty unwieldy.
How can I go about setting up a library with multiple entry files that are all exported? Or am I going about something the wrong way here?
Use named exports to export multiple classes in JavaScript, e.g. export class A {} and export class B {} . The exported classes can be imported by using a named import as import {A, B} from './another-file. js' . You can have as many named exports as necessary in a file.
webpack.config.js module. exports = { entry: { main: './path/to/my/entry/file. js', }, }; We can also pass an array of file paths to the entry property which creates what is known as a "multi-main entry".
Every module can have two different types of export, named export and default export. You can have multiple named exports per module but only one default export.
To export multiple functions in JavaScript, use the export statement and export the functions as an object. Alternatively, you can use the export statement in front of the function definitions. This exports the function in question automatically and you do not need to use the export statement separately.
I think you'd better use a entry.js file to indicate how you organize your serveral modules.
import Apples from './apples';
import Oranges from './oranges';
export {
Apples,
Oranges
};
By the way, if you don't want to write such stupid codes by your own, use Gulp/Grunt to generate the file 'entry.autogenerated.js' by some logic then run webpack with the entry 'entry.autogenerated.js'.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With