Unknown developer
Unknown developer

Reputation: 5960

Export module via Webpack

I am working on a React app. In index.js am exporting some variables, e.g.

export const a="Hello";
export const b=[1,2,3];

In webpack.config.js:

...
output: {
 ...
 library: "myApp",
 libraryTarget: "window"
},
...

I know window.myApp is now a module which includes all the exported variables from index.js. What I do not know is how the above works. How this module is being created and why it includes only the exports from index.js and not other files as well? How, may I include exports from another specific file?

Upvotes: 2

Views: 1384

Answers (2)

0xFK
0xFK

Reputation: 2728

You have two solution to include other files

First is to use multiple entries in your webpack module

module.exports = {
    // mode: "development || "production",
    entry: {
        A: "./CompA",
        B: "./CompB"
    },

Second approach is use one entry like your solution, but need to add wrappere.js

wrapper.js

import * as a from './CompA.js'
import * as b from './CompB.js'

export a,b 

And your wrapper become the single entry, where you can access later wrapper.a,wrapper.b

module.exports = {
        // mode: "development || "production",
        entry: {
            app: "./wrapper.js",

        },

Upvotes: 0

Shubham Khatri
Shubham Khatri

Reputation: 281950

Your module is being created based on the entry configuration and the other modules and plugins that you configure and is converted to a build file based on the configuration provided in the output config of webpack.

library setup is tied to the entry configuration so if you specify the entry to be index.js, your exports from within the index.js are available within the build

In order to also expose exports from other files, you can import and export them from the index file like

    export { default as SomeFunction} from 'some-function.js';

According to the webpack docs:

For most libraries, specifying a single entry point is sufficient. While multi-part libraries are possible, it is simpler to expose partial exports through an index script that serves as a single entry point. Using an array as an entry point for a library is not recommended.

libraryTarget specifies how the module is exposed. For instance in your case your module is exposed on the window object.

You can expose the library in the following ways:

  • Variable: as a global variable made available by a script tag (libraryTarget:'var').

  • This: available through the this object (libraryTarget:'this').

  • Window: available through the window object, in the browser (libraryTarget:'window').

  • UMD: available after AMD or CommonJS require (libraryTarget:'umd').

If library is set and libraryTarget is not, libraryTarget defaults to var as specified in the output configuration documentation. See output.libraryTarget there for a detailed list of all available options.

Upvotes: 4

Related Questions