Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

webpack export classes from multiple entry files

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?

like image 511
Jason Farnsworth Avatar asked Sep 10 '15 21:09

Jason Farnsworth


People also ask

How do I export multiple classes?

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.

How do you get multiple entry points on webpack?

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".

Can you export default multiple things?

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.

How do I export multiple functions?

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.


1 Answers

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'.

like image 146
Xin Liu Avatar answered Sep 28 '22 06:09

Xin Liu