Webpack PnP Externals

raw JSON →
1.1.0 verified Sat Apr 25 auth: no javascript

Webpack plugin (v1.1.0) to exclude Yarn Plug'n'Play (PnP) modules from the bundle, intended for backend bundles using Yarn PnP. Works with Webpack 4 and 5. It complements webpack-node-externals by resolving PnP packages to their virtual locators, preventing bundling of dependencies that should be loaded at runtime. It supports include/exclude filters and custom import types. Lightweight, no runtime dependencies. Minimal maintenance frequency as of 2023.

error Error: Cannot find module 'webpack-pnp-externals'
cause Package not installed or not in node_modules.
fix
Install: npm install -D webpack-pnp-externals
error TypeError: WebpackPnpExternals is not a function
cause Using import statement in CJS context, or misspelling the import.
fix
Use require syntax: const { WebpackPnpExternals } = require('webpack-pnp-externals');
error Error: Externals function must return a string, array, or object.
cause WebpackPnpExternals() returned a non-standard value, likely due to invalid options.
fix
Check that options.include/exclude are valid types; ensure WebpackPnpExternals() is called with parentheses.
gotcha WebpackPnpExternals() must be called (returning a function) in the externals array; passing the reference without invoking will fail.
fix Use WebpackPnpExternals() with parentheses, not WebpackPnpExternals.
gotcha Only works with Yarn Classic (v1) PnP; Yarn Berry (v2+) has different PnP resolution that is not supported.
fix For Yarn Berry, consider using webpack-plugin-yarn-pnp-externals or manually configuring externals with locator logic.
gotcha The 'include' and 'exclude' options can be a string, RegExp, function, or array. Using a string matches the request exactly, not a substring.
fix Use RegExp for substring matching, e.g., include: /^lodash/.
deprecated Webpack 4 is no longer supported by the package explicitly; but it still works. No deprecation warnings.
fix Upgrade to Webpack 5 for full compatibility.
npm install webpack-pnp-externals
yarn add webpack-pnp-externals
pnpm add webpack-pnp-externals

Shows how to use WebpackPnpExternals in webpack config to externalize Yarn PnP packages with include/exclude filters and custom import type.

const { WebpackPnpExternals } = require('webpack-pnp-externals');

module.exports = {
  target: 'node',
  externals: [
    WebpackPnpExternals({
      include: /^lodash/,
      exclude: ['lodash.omit'],
      importType: 'commonjs2'
    })
  ]
};