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.

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

Dependencies under "dependencies" are generally related to project code and builds, and if these third-party dependencies are declared under "devDependencies", then there will be missing dependencies in production environments.

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" and "peerDependencies" are not bundled by Modern.js Module.

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": "^17"
  },
  // or
  "peerDependencies": {
    "react": "^17"
  }
}

When a react dependency is used in the source code:

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

The react code is not bundled into the artifact:

dist/index.js
import React from 'react';
console.info(React);

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

Exclude specified third-party dependencies

We mentioned above the use of the buildConfig.autoExternal API, and buildConfig.externals can control which third-party dependencies to handle the project's dependencies in a more granular way.

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

In this case, it is likely that some dependencies are not suitable for packaging. If this is the case, then you can handle it as follows.

epxort default defineConfig({
  buildConfig: {
    autoExternal: false,
    externals: ['pkg-1', /pkg-2/],
  }
});