Tree-shaking with getInitialProps? #12607
-
Hello, I am trying to enable tree-shaking for a next app, I came across some release notes from Next 9.x that say tree-shaking is now possible but I don't see how this can be enabled or if it's default behavior, is it only available for newer fetching apis getStaticProps/getServerSideProps We only have getInitialProps now and would like to know if tree-shaking is possible, running Next 9.3.5 |
Beta Was this translation helpful? Give feedback.
Replies: 4 comments 3 replies
-
If you mean this: import fs from 'fs';
export async function getStaticProps(context) {
const file = fs.readFileSync(...); // fs will be removed from the bundle
...
} Then no, it won't work with What you can do instead is checking if the code is running in the server, then the imports inside the if will be removed from the client bundle: Page.getInitialProps = async ctx => {
if (typeof window === 'undefined') {
// This will only run in the server, and the `if` will be evaluated at build-time,
// not bundling `fs` in the client-side code
const fs = require('fs');
const file = fs.readFileSync(...);
}
...
} |
Beta Was this translation helpful? Give feedback.
-
Thanks @rafaelalmeidatk for your answer, that's not what I meant. I was asking about regular tree-shaking that webpack 4 & 5 has, where unused exports are not loaded with other js loaded on each page (which bloats the payload for each getInitialProps unfortunately) |
Beta Was this translation helpful? Give feedback.
-
Tree shaking is enabled in Next.js through webpack automatically. You don't need to configure anything to leverage it, it works automatically. As @rafaelalmeidatk said tree shaking of the data fetching solution was previously not possible because of the way |
Beta Was this translation helpful? Give feedback.
-
I figured, the thing is some packages weren't tree shakeable I had to fix them and I confirm tree-shaking is working through webpack thanks |
Beta Was this translation helpful? Give feedback.
Tree shaking is enabled in Next.js through webpack automatically. You don't need to configure anything to leverage it, it works automatically. As @rafaelalmeidatk said tree shaking of the data fetching solution was previously not possible because of the way
getInitialProps
was ran server and client side. getStaticProps/getServerSideProps are tree shaken from the browser bundle, which allows you to use any Node.js apis there.