WendellLiu
WendellLiu

Reputation: 317

How to bundle module without dependencies for publishing npm package

Recently, I developed a React component and want to publish it.

In this package,

"dependencies": {
  "react": "^0.14.6",
  "react-dom": "^0.14.6",
  "react-timer-mixin": "^0.13.3"
}

When I build the package by webpack command, I will get a bundle containing react, react-dom and react-timer-mixin.
It seems wrong for this practice...

Thus, my question is how to build package without dependencies for publishing.

*I think the chuck-vendor method to separate main bundle and dependencies is for multiple bundle file. But my requirement is for building the lib.

Upvotes: 3

Views: 3039

Answers (2)

Quentin Roy
Quentin Roy

Reputation: 7887

If you are building a library, you need to register these dependencies as externals.

To summarise, just add the externals property in your webpack config and set it to an array containing the names (string) of the modules to exclude.

A more complex case could require you to specify how should be imported your dependencies in function of the import system. You can achieve this using an object.

Here is the official example:

module.exports = {
    output: {
        libraryTarget: "umd"
    },
    externals: [
        "add",
        {
            "subtract": {
                root: "subtract",
                commonjs2: "./subtract",
                commonjs: ["./math", "subtract"],
                amd: "subtract"
            }
        }
    ]
}

See here for more information about library and externals.

If you are using ES 2015 and babel 6, you may also encounter an issue with the export of the library being a module object instead of what you want (e.g. your component). Have a look at this question to solve it.

Upvotes: 5

Grgur
Grgur

Reputation: 7382

Perhaps you should use peerDependencies instead. Then you can build without webpack for publishing. If you use ES6, all you need is a babel transpilation step.

Something like this is often enough

babel ./src -d ./lib

Peer dependencies will let npm know the project using your package should have those dependencies installed.

Upvotes: 0

Related Questions