Each page in NextJS has a nearly identical JavaScript bundle size

After using NextJS for a considerable amount of time, I finally decided to take a closer look at the build folder and the console output when the build process is successful. To my surprise, I noticed something peculiar during one of these inspections.

Incorporating TypeScript into my project, I created a babel configuration that utilizes TS's settings to enable absolute paths functionality. Essentially, my components are imported using an alias ~/components, which points to ./src/components. This approach is consistent throughout the entire application, with various other absolute paths being utilized as well. However, upon building my app, I observed an interesting pattern:

https://i.sstatic.net/YTEFY.png

Every page within the app seemed to have a similar file size, including the seemingly simple 'about' and '404' pages, both exhibiting unexpectedly large sizes. My assumption was that the issue stemmed from importing modules using absolute paths, resulting in every page linking to a JavaScript file containing the entire application code. Unfortunately, I've been unable to find relevant resources online to assist me in optimizing these pages effectively. I'm uncertain whether the required adjustments should be made in webpack or babel configurations. Hence, I appeal for assistance in identifying any additional configurations necessary to ensure each page only loads the essential JavaScript code it requires.

Below are snippets of my TypeScript and Babel configurations for reference:

TypeScript Configuration:

{
  "compilerOptions": {
    // Configuration details
  },
  "exclude": ["node_modules"],
  "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"]
}

Babel Configuration:

{
  "presets": ["next/babel"],
  "plugins": [
    // Plugin details
  ]
}

Answer №1

After conducting some research, I discovered that when importing components from a file that exports multiple React components, the module bundler includes all components by default, resulting in a large bundle size. This happens because the bundler cannot determine which components will be used and thus packages them all together.

In my case, using Next.js with components from the same directory led to a massive bundle size as Next (or Webpack) could not split them up. This meant that every page included the entire set of components from the directory, regardless of whether they were actually being used on that page.

To address this issue, I implemented Tree Shaking in my Webpack configuration. Tree Shaking removes any unused code during bundling, resulting in smaller bundle sizes. It is important to note potential side effects when implementing Tree Shaking. Here is the difference in bundle size after implementing Tree Shaking:

https://i.sstatic.net/jew9i.jpg

Alternatively, one can opt for relative imports instead of Tree Shaking. However, this approach may not be suitable for larger applications.

Answer №2

If you check out the pull request here, all the details are explained.

The update in this pull request changes a page's "Size" to only include its own dependencies.

Additionally, a new "First Load" column has been added which combines shared size and color coding has been moved to that column (as first load is crucial for budgets).

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How to use sinon to create a mock for an independently imported function

Is there a way to successfully mock the axios import using sinon and then set expectations? Here is my attempted code: import axios from 'axios'; axiosMock = sinon.mock(axios); However, the expectation does not pass: describe('Custom test ...

Is there a way to prevent a bootstrap modal from opening?

Recently, I encountered an issue with a button on my webpage: <a data-toggle="modal" href="#influencerModal" class="btn btn-primary influencer-card">Influencer Profile</a> I wanted to prevent the modal from opening when the button was clicked ...

Can you explain the significance of the "@" symbol in the `import from '@/some/path'` statement?

When I use IntelliJ IDEA to develop a web application in TypeScript, the autocomplete feature suggests imports from other files within my project like this: import {Symbol} from '@/components/Symbol'; I am curious about the significance of the @ ...

Integrate Vue Login Functionality using Axios HTTP Requests

Hello everyone! I am new to Vue and currently struggling with making an HTTP Request to my backend. When I check the browser console, I can see the access token retrieved from /login endpoint but when I try to fetch data from api/users, it returns "Token ...

sending a collection of image data arrays wrapped in FormField objects from Angular to Express

I am facing a challenge while trying to upload two FormField objects along with form data to express. I am having trouble using the multer library in express to extract this data from the request. While I can access the form data, the FormField objects re ...

Loading animation reminiscent of a whirlpool, similar to the movement

In my quest for the perfect animation, I have scoured far and wide. Unfortunately, the one I found at http://jsfiddle.net/pedox/yed68/embedded/result/ is created using css, which many browsers do not yet support fully. I also explored , but found it to be ...

Converting a JSON PHP array into Javascript

How can I convert this PHP array named $data into JSON using json_encode? Whenever I try to do so in JavaScript by writing... var myJson = <?php echo json_encode($data) ?>; console.log(myJson); I encounter errors. I am curious about any restrictio ...

I am searching for a tool in ThreeJS that functions similar to AxisHelper, possibly a Helper class or utility

While working with Three.js, I have come across many helpful Helper classes that greatly simplify displaying and modifying the scene. However, there is one particular tool that I am struggling to find again. It is similar to the AxisHelper, but it includes ...

The alarm feature is malfunctioning

I have been struggling with a simple alarm application that I created using jQuery and Javascript. The issue lies in the alarm functionality not working as expected. Below is the relevant code snippet: var today = new Date(); var h = today.getHours(); var ...

The struggle between Node.js 404 errors and Angular's URL refresh issue

I am currently developing a Node.js and AngularJS application. I encountered an issue where a page loads successfully when the URL is entered, but then I added a script to redirect to a 404 error page. Now, only one of the criteria works at a time - either ...

Troubleshooting the issue with the default dropdown select in AngularJS

var jsonData ='[ {"type":"product", "id":1,"label":"Color", "placeholder":"Select Jean Color", "description":"", "defaultValue":"Brown", "choices":[{ "text":"Denim", "price":"$0.00", "isSel ...

Sauce Labs encountering issues when running JavaScript code

Currently, I am using Selenium WebdriverJs along with Mocha to conduct tests on Sauce Labs via Travis CI. After isolating the issue without any project dependencies, I am seeking help. The interesting observation is that defining an additional object with ...

Loading dynamic components asynchronously in Vue 3 allows for improved performance and enhanced user experience

My goal is to dynamically display components based on their type. Here's how I'm approaching it: I have several similar components that should show different content depending on their type. Using the defineAsyncComponent method, I can easily im ...

Creating a rhombus or parallelogram on a canvas can be easily achieved by following these simple

I'm new to working with the canvas element and I want to create some shapes on it. Can someone provide me with guidance on how to draw a Rhombus or Parallelogram on a canvas? Something similar to what is shown in this image: https://i.stack.imgur.c ...

Error: Attempting to access the 'url' property of an undefined variable, despite specifically checking for its undefined status

Within my React application, I am utilizing the following state: const [functions, setFunctions] = useState([{}]); I have created a test to check if a specific property is undefined: if (typeof functions[functionCount].url !== "undefined") { ...

Load Angular template dynamically within the Component decorator

I am interested in dynamically loading an angular template, and this is what I have so far: import { getHTMLTemplate } from './util'; const dynamicTemplate = getHTMLTemplate(); @Component({ selector: 'app-button', // templat ...

Error Alert: "Invariant Violation" detected in a TypeScript program utilizing React

When attempting to implement the react-collapse component in my TypeScript application along with a custom d.ts file, I encountered the following error: Warning: React.createElement: type should not be null, undefined, boolean, or number. It should be a ...

Swap out the selector of an Ionic2 component with its contents

I am utilizing Ionic2 along with TypeScript. Let's assume I desire a custom component to include the content of an ion-menu. <sidemenu></sidemenu> //This sidemenu will contain the ion.menu. <ion-nav id="nav" [root]="rootPage" ...

Simple steps to load various json files into separate json objects using node.js

I am new to working with Json and node.js My goal is to load a json file into a JsonObject using node.js, but I have been struggling to accomplish this task. I have created two files, one named server.js and the other jsonresponse.json. My objective is t ...

The state change in React-Redux does not trigger a re-render

I successfully developed a large react-redux application with an undo feature in one component. While the state updates properly and re-renders the component along with its children, I noticed that the component's position on the page remains unchange ...