Skn0tt / nextjs-nestjs-integration-example

https://nextjs-nestjs-integration-example.now.sh
156 stars 36 forks source link

Doesn't work when babel is disabled (babel is no longer used in next v12) #35

Open R-Bower opened 2 years ago

R-Bower commented 2 years ago

When NextJS v12 is used without a babel configuration, this solution fails to perform service injections.

Example:

// number.service.ts
import {Injectable} from "@nestjs/common"

@Injectable()
export class NumberService {
  getNumber(): number {
    return Math.random() * 100
  }
}
// number.controller.ts
import {Controller, Get} from "@nestjs/common"

import {NumberService} from "./number.service"

@Controller("randomNumber")
export class NumberController {
  constructor(private numberService: NumberService) {}

  @Get()
  randomNumber(): number {
    return this.numberService.getNumber()
  }
}
// number.module.ts
import {Module} from "@nestjs/common"

import {NumberController} from "./number.controller"

@Module({
  controllers: [NumberController],
})
export class NumberModule {}

[Nest] 8972 - 02/11/2022, 4:02:40 PM ERROR [ExceptionsHandler] Cannot read properties of undefined (reading 'getNumber')

I understand that there's transformation happening with babel. When these transformations aren't applied, services aren't injected properly. There are likely errors with every type of dependency injection. Not sure on how to proceed. Let me know if you'd like a replication repo.

R-Bower commented 2 years ago

Managed to fix this by modifying Next's webpack config. The solution is to force webpack to use the babel config for the NestJS code.

// in next.config.js
webpack: (config) => {
    config.module.rules.push({
      // apply babel to the NestJS files.
      test: /.*\/backend\/.*\.ts/,
      use: {
        loader: "babel-loader",
        options: {
          plugins: [
            "babel-plugin-transform-typescript-metadata",
            ["@babel/plugin-proposal-decorators", {legacy: true}],
            "babel-plugin-parameter-decorator",
          ],
          presets: [
            [
              "next/babel",
              {
                "preset-typescript": {
                  onlyRemoveTypeImports: true,
                },
              },
            ],
          ],
        },
      },
    })
}
Skn0tt commented 2 years ago

That makes sense! Another solution would be to place this .babelrc in your project root:

{
  "presets": ["next/babel"]
}

That will make Next v12 use the Babel transform again.

future-mine commented 2 years ago

Can I add typeorm? image I am getting this error. The problem is that the Nestjs server is built in a file, as I see. How can I resolve this?

Skn0tt commented 2 years ago

Hi @future-mine! Please open a separate issue and provide detailed steps on how to reproduce this (a reproduction repository would be great!). That'd make it a lot easier to help you :)