webpack-require-weak

raw JSON →
1.0.1 verified Sat Apr 25 auth: no javascript maintenance

Utility for using webpack's resolveWeak to conditionally require modules in webpack bundles. Version 1.0.1, no active release cadence. Key differentiator: enables optional module loading without webpack bundling the module, useful for universal modules that work both in webpack and Node.js. Typically used alongside `is-webpack-bundle`.

error Error: Cannot find module 'webpack-require-weak'
cause Package not installed or not in node_modules.
fix
Run: npm install webpack-require-weak
error TypeError: webpackRequireWeak is not a function
cause Default import incorrect in certain environments.
fix
Use: const webpackRequireWeak = require('webpack-require-weak').default;
gotcha webpack-require-weak requires webpack's resolveWeak which is only available inside a webpack bundle. Using it outside webpack will throw.
fix Always check isWebpackBundle before calling webpackRequireWeak.
gotcha The return value from webpackRequireWeak may be null if the module cannot be resolved at runtime.
fix Always check for null or undefined before using the returned module.
gotcha The package has no TypeScript types. Using with TypeScript may require custom type definitions.
fix Declare module in a .d.ts file: declare module 'webpack-require-weak';
npm install webpack-require-weak
yarn add webpack-require-weak
pnpm add webpack-require-weak

Shows conditional require using webpack's resolveWeak to avoid bundling the module in webpack, falling back to normal require in Node.

const isWebpackBundle = require('is-webpack-bundle');
const webpackRequireWeak = require('webpack-require-weak');

let myModule;
if (isWebpackBundle) {
  myModule = webpackRequireWeak(require.resolveWeak('./path/to/module'));
} else {
  myModule = require('./path/to/module');
}

// Ensure webpack doesn't bundle the module conditionally
if (myModule) {
  myModule.doSomething();
}