How to configure webpack to exclude certain modules from a library?

I have a React app that imports a library (in the node_modules directory, of course).

The name of the library is @lib/schema.

In the react app, modules of this library are imported like so:

import { module_name } from "@lib/schema"

There is a certain file in the @lib/schema that is currently being included in the final bundle, which is located in this path:

src/path/to/large_file.js

The file is never used by the app and thus unnecessarily increases the size of the bundle.

The React app currently uses react-scripts to create the bundle.

Questions:

  1. If the React app were to continue to use react-scripts, how do I configure it to exclude src/path/to/large_file.js?
  2. If the React app were to use webpack, how do I configure it to exclude src/path/to/large_file.js?

Upvotes: 1

Views: 70

Answers (2)

Estus Flask
Estus Flask

Reputation: 222979

react-scripts belongs to CRA, which uses Webpack. If large_file isn't used in the app, it's not supposed to be in a bundle. For a dynamic import like require(`src/path/to/${file_name}`) all files inside to/ are included to a bundle.

The easiest way to avoid this is to structure a project in a way unwanted file won't be matched by dynamic import, i.e. to/ contains only the files in use.

It's possible to change CRA's Webpack config with tools like react-app-rewired or Craco. Webpack IgnorePlugin or ContextReplacementPlugin can be used to exclude a module when it's already included.

Alternatively, webpackExclude option can be used in a comment to annotate an import.

Upvotes: 1

Sandeep Singh
Sandeep Singh

Reputation: 99

If you want to completely avoid importing the file, you can create an alias for it that points to an empty module.

1.Modify your Webpack configuration:

In your webpack.config.js, add an alias for the large file:

const path = require('path');

module.exports = {
// ... other configurations
resolve: {
alias: {
  '@lib/schema/src/path/to/large_file.js': path.resolve(__dirname, 
'path/to/empty.js'),
},
},
};

2.Create an empty module:

Create a file named empty.js in the specified path (e.g., path/to/empty.js)

Conclusion By following the above methods, you can effectively exclude src/path/to/large_file.js from your final bundle, whether you are using react-scripts or a custom Webpack configuration. Choose the method that best fits your project's setup.

Upvotes: 1

Related Questions