When using Babel 7, we typically do not compile the contents of the node_modules folder, and several reasons account for this:
-
Performance Considerations: The
node_modulesfolder typically contains a large number of files. If Babel were to compile these files, it would significantly increase the build time. For most projects, this additional compilation time is not cost-effective. -
ES5 Compatibility of Dependency Packages: The vast majority of libraries published on NPM have already been precompiled into ES5-compatible code. This means they can run in most modern browsers without further transformation. The primary purpose of this is to ensure broad compatibility of the libraries while reducing the configuration burden on end users (developers).
-
Avoiding Duplicate Compilation: If each project compiles its dependencies within
node_modules, each dependency would be compiled multiple times, not only wasting computational resources but also potentially leading to errors and inconsistent behavior. -
Configuration Complexity: Having Babel process code within
node_modulesmay require complex configurations, especially when dealing with different tools and transpilation settings. Ignoring these files by default can simplify the Babel configuration for the project.
Example Illustration
Assume we are developing a frontend application using React. Most React component libraries, such as material-ui or react-bootstrap, have already been compiled into ES5 code, so they can be used directly in our application without further compilation by Babel. If Babel recompiles these libraries, it not only increases the build time but may also introduce compilation discrepancies due to different Babel versions or plugin configurations.
Summary
Therefore, it is generally recommended to exclude the node_modules directory in Babel's configuration. This not only improves build performance but also avoids unnecessary compilation issues and configuration complexity. Of course, if there are specific needs, such as compiling a particular untranspiled ES6 module, specific configurations can be used to compile certain dependencies.