lcsth
lcsth

Reputation: 108

Array(n) has wrong length on production in Next.js

I am trying to create an array of some specific length in TypeScript, but anytime I run my app in production mode (aka the minified version), the generated array length is off by one. To be concrete: when I run

console.log(Array(3));

in dev mode, I get (3) [empty x 3], but after building and running the generated file, I get (2) [empty x 2].

I am running a Next.js app (version 12.2.0) with the standard build and start commands (next dev, next build and next start).

Does anyone have an idea why this happens?

Minimal steps to reproduction

  1. run npx create-next-app@latest in an empty directory with default values
  2. in /pages/index.js, add console.log(new Array(3)) before the return statement
  3. run yarn dev for output (3) [empty x 3] on localhost:3000
  4. run yarn build && yarn start for output (2) [empty x 2] on localhost:3000

Upvotes: 5

Views: 667

Answers (1)

juliomalves
juliomalves

Reputation: 50298

This seems related to SWC Minification, which transforms Array(3) into [,,] (running console.log([,,]) outputs (2) [empty x 2]).

There's an on-going SWC minify feedback discussion to report these kind of issues.


You can either disable swcMinify in the next.config.js altogether.

module.exports = {
    swcMinify: false
}

Or, keep swcMinify enabled but use something like the following until this gets fixed.

Array.from({ length: 3 })

Upvotes: 5

Related Questions