Tips for minimizing Ant Design bundle size with TypeScript in a Next.js project using Less styles

While working on my Next.js application, I observed that the file sizes are quite large during the build process. Interestingly, the size remains consistent across pages, indicating that the entire AntD package is being imported.

Page                                       Size     First Load JS
┌ λ /                                      3.21 kB         324 kB
├   /_app                                  0 B            86.6 kB
├ ○ /404                                   194 B          86.8 kB
├ λ /account                               7.92 kB         314 kB
├ λ /announcement/[reference]              20.8 kB         338 kB
├ λ /api/announcements                     0 B            86.6 kB
└ ...

I have made attempts to modify various configuration files like package.json, tsconfig.json, next.config.js, .babelrc.js in the hope of optimizing the build output. However, every time I feel like I am making progress, I encounter the error message below. The goal is to utilize the es version of AntD instead of the lib.

SyntaxError: Cannot use import statement outside a module

Here is the configuration settings I am using:

// .babelrc.js

module.exports = {
    presets: [
        ['next/babel']
    ],
    plugins: [
        ['import',
            {
                libraryName: 'antd', style: true, libraryDirectory: 'es',
            }
        ]
    ],
};
// next.config.js
const withNextTranslate = require('next-translate');
const withAntdLess = require('next-plugin-antd-less');

module.exports = withNextTranslate(withAntdLess({
  lessVarsFilePath: "./styles.antd.less",
  cssLoaderOptions: {},
  images: {
    domains: ["storage.googleapis.com"],
  },

  webpack: (config) => {
    config.module.rules.push(
      {
        test: /\.(png|jpg|gif|svg)$/,
        use: [
          {
            loader: 'url-loader',
            options: {
              limit: 8000,
              name: '[name].[hash:7].[ext]'
            }
          }
        ]
      }
    )
    return config;
  }
}));
// tsconfig.json
{
  "compilerOptions": {
    "target": "es5",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "allowJs": true,
    "skipLibCheck": true,
    "strict": false,
    "forceConsistentCasingInFileNames": true,
    "noEmit": true,
    "esModuleInterop": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "jsx": "preserve"
  },
  "include": [
    "next-env.d.ts",
    "**/*.ts",
    "**/*.tsx"
  ],
  "exclude": [
    "node_modules"
  ]
}

In addition to this, I've set the import in the .less file as

@import '~antd/es/style/themes/default.less'; 

If anyone has any insights on what might be wrong with these configuration files, please let me know.

Answer №1

If you're not specifically looking for webpack configurations, here are some alternative suggestions:

  • Instead of importing the entire library, try manually importing components like this:
    import Row from "antd/lib/row"
    . I opted for manual imports as opposed to tree shaking due to time constraints.
  • Consider minifying your code with tools like the minify-simplify babel plugin.

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

Subtracting Arrays Containing Duplicates

Imagine having two arrays defined like this: const A = ['Mo', 'Tu', 'We', 'Thu', 'Fr'] const B = ['Mo', 'Mo', 'Mo', 'Tu', 'Thu', 'Fr', 'Sa&ap ...

Define an object type in Typescript that includes both specified properties and an unlimited number of unspecified properties

I'm attempting to create a custom data type using the code below, but it's not working: type CustomDataType { [key: string]: CustomDataType; isValid: boolean; errors?: string[]; } My goal is to have a CustomDataType with an isValid propert ...

What is the best way to access the next-auth session using getStaticPaths and getStaticProps in dynamic routing scenarios?

I am currently working on implementing dynamic routing in a NextJS application. I need to retrieve the token from next-auth in order to make axios requests to an API and fetch data from getReport and getReports (located in /reports.js). However, I am facin ...

How can you choose the active tab when using Material UI Tabs in conjunction with React Router?

Combining React, Material-UI, and React-Router, I've successfully integrated React-Router with Material-UI tabs. Everything functions properly within the app itself. However, there's a minor issue when a user directly enters a specific route in t ...

Modify visibility within a subclass

Is there a way to modify property visibility in a child class from protected to public? Consider the following code snippet: class BaseFoo { protected foo; } class Foo extends BaseFoo { foo = 1; } new Foo().foo; It seems that this change is pos ...

Passing data from a parent component to a child component in Next.JS 13

Struggling to make NextJS work seamlessly with props and passing them between components? It feels like a React-specific challenge, but after scouring Google for answers, the results are scarce. My goal is simple: send a useState value along with its sette ...

bringing TypeScript functions into another file

I am attempting to include a function in my main.ts file, but I keep encountering errors like 'is not a module' or 'unexpected import token' when I try to execute my file using node main.ts. These functions are not part of any node mod ...

The data does not have a property named 'formData' according to the type 'Event'

Encountered an issue while attempting to compile my TypeScript code: typescript Property 'formData' does not exist on type 'Event'? formElem.addEventListener("submit", (e) => { // prevent default action on form submiss ...

Is it suitable to use React Server Components for retrieving a partial webpage according to client state?

Currently, I am in the process of developing a Next.js 14 application using the App Router. My goal is to integrate a 'popup' component within a marker's onClick event handler in the react-map-gl library. The content of the 'info box&ap ...

What is the best way to combine index signatures with established properties?

Imagine a scenario where an interface has certain defined properties with specific types, but can also include additional properties with unknown keys and various other types. Here is an example: interface Bar { size: number; [key: string]: boolean | s ...

Setting up d3 to function properly with Angular2 and TypeScript

Attempting to integrate the d3 library into an Angular 2 TypeScript project. I installed d3 using npm install d3 and the typings using typing install d3 --save, but when trying to start the local server for the project (tsc && concurrently "npm ru ...

Modify the code to use a BehaviorSubject subscribing to an Observable

Currently, I am in the process of learning Angular2 and RxJS by studying someone else's application. The application consists of two modules: asObservable.ts export function asObservable(subject: Subject) { return new Observable(fn => subject ...

How can the button press, release, drag, and drop events be implemented in Ionic?

I have been working on adding a recording feature that allows for recording when a button is pressed and stops when it is released. I decided to use the ionic-long-press plugin for this functionality. However, I have noticed that it does not support drag ...

What could be causing the Angular router outlet to not route properly?

Check out this demo showcasing 2 outlets (Defined in app.module.ts): <router-outlet></router-outlet> <router-outlet name="b"></router-outlet> The specified routes are: const routes: Routes = [ { path: 'a', com ...

Can you provide input to the reducer function?

In the creator, an action is defined like this: export const actionCreators = { submitlink: (url: string) => <SubmitLinkAction>{ type: 'SUBMIT_LINK' } } In the component that calls it: public render() { return <div> ...

Creating UI Bootstrap dropdowns using ng-repeat on the fly

As a newcomer to AngularJS and UI Bootstrap, I am facing an issue with adding dropdowns dynamically using ng-repeat. The main problem lies in the fact that when one dropdown is clicked, it triggers all of them simultaneously. It seems like there is some mi ...

Are your forms acting out? React Hooks and Typescript collaboration might be the answer!

After spending months using class components, I decided to try out Hooks and Typescript for the first time. My current challenge is setting up a search bar as a controlled form. No matter what I do, I can't seem to achieve this. Additionally, when t ...

When running npx ts-lint in a Docker environment, an error occurs stating that the module 'typescript' cannot be found

In the process of setting up a dockerized development environment for a node/typescript API project, I am aiming to have everything run within Docker without the need for node, npm, or modules installed on the host system. The main objective is to isolate ...

What significance does the colon hold in JavaScript syntax when used after a function declaration?

After inspecting the code of the Facebook F8 app, I noticed that there is a colon (:) following the function declaration. function setup(): React.Component { ... } Can you clarify the significance of this syntax? Is this related to inheritance? ...

Bundle with no crucial dependencies

In need of creating a package that offers abstractions relying on the IObservable interface, I require two external classes mimicking the behavior of Subject<T> and BehaviorSubject<T> from rxjs. However, it is essential for me to avoid tightly ...