Handle Third-Party Dependencies

Generally, third-party dependencies required by a project can be installed via the install command in the package manager. After the third-party dependencies are successfully installed, they will generally appear under dependencies and devDependencies in the project package.json.

package.json
{
  "dependencies": {},
  "devDependencies": {}
}

Dependencies under "dependencies" are generally required for the package in runtime, and if these third-party dependencies are declared under "devDependencies", then there will be missing dependencies in production runtime.

In addition to "dependencies", "peerDependencies"can also declare dependencies that are needed in the production environment, but it puts more emphasis on the existence of these dependencies declared by "peerDependencies" in the project's runtime environment, similar to the plugin mechanism.

Default handling of third-party dependencies

By default, third-party dependencies under "dependencies", "optionalDependencies" and "peerDependencies" are not bundled by Rslib.

This is because when the npm package is installed, its "dependencies" will also be installed. By not packaging "dependencies", you can reduce the size of the package product.

If you need to package some dependencies, it is recommended to move them from "dependencies" to "devDependencies", which is equivalent to prebundle the dependencies and reduces the size of the dependency installation.

Example

If the project has a dependency on react.

package.json
{
  "dependencies": {
    "react": "^18"
  },
  // or
  "peerDependencies": {
    "react": "^18"
  }
}

When a react dependency is used in the source code:

src/index.ts
import React from 'react';
console.info(React);

The react code will not be bundled into the output:

dist/index.js
import * as __WEBPACK_EXTERNAL_MODULE_react__ from 'react';
console.info(__WEBPACK_EXTERNAL_MODULE_react__['default']);

If you want to modify the default processing, you can use the following API:

Exclude specified third-party dependencies

The configuration described above allows you to implement more fine-grained handling of third-party dependencies.

For example, when we need to leave only certain dependencies unbundled, we can configure it as follows.

TIP

In this case, some dependencies may not be suitable for bundling. If so, you can handle it as follows.

export default defineConfig({
  lib: [
    {
      // ...
      autoExternal: true,
      output: {
        externals: ['pkg-1', /pkg-2/],
      },
      // ...
    },
  ],
});