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:
- If the React app were to continue to use
react-scripts
, how do I configure it to excludesrc/path/to/large_file.js
? - If the React app were to use
webpack
, how do I configure it to excludesrc/path/to/large_file.js
?
2
Answers
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:
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.
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 likerequire(`src/path/to/${file_name}`)
all files insideto/
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
orContextReplacementPlugin
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.