Bundle JavaScript Application, libraries and all dependencies
Wednesday, February 19, 2020
Bundle JavaScript Application, libraries and all dependencies
In an effort to reduce network requests web applications should bundle JavaScript, and the necessary libraries and dependencies. Network requests should be considered expensive operations, and as such, avoiding network requests can increase the performance of our applications.
Why?
What you may not be aware of is that a network request is made for each external JavaScript that you require using a <script>
tag or that is imported via the import()
or require()
syntax. For a few external JavaScript files, this is fine. However, many modern web applications that use JavaScript require and import dozens, perhaps hundreds or more, of external libraries and dependencies.
Resources
There are several open-source resources and libraries that are available for bundling your JavaScript into a single bundle, or split into several bundles based on your configuration.
One of the most popular bundling tools out there is called webpack. In addition to bundling your code, webpack will also perform tree-shaking to eliminate dead or unused code from your final bundles.
Another widely used bundling tool is rollup that also performs very efficient tree-shaking of your bundles.
Large Applications
Bundling applications that are larger than 1MB uncompressed into a single bundle may be counterproductive. In this scenario consider using webpack's code splitting feature in order to split your code into multiple bundles.
Instructions
use bundling tools like webpack and rollup to bundle JavaScript into smaller chunks
splitting large bundles into smaller chunks
lazy loading chunks that are not necessary for displaying the current route of the application
prefetching lazy loaded chunks
network requests are expensive and as a result avoiding multiple requests can decrease the time-to-interactivity (TTI) of web applications
Code Examples
Sample webpack.config.js file for bundling TypeScript
const path = require('path');
module.exports = {
entry: './src/index.ts',
devtool: 'inline-source-map',
module: {
rules: [
{
test: /\.tsx?$/,
use: 'ts-loader',
exclude: /node_modules/
}
]
},
resolve: {
extensions: [ '.tsx', '.ts', '.js' ]
},
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
}
};
Have a question or comment?