Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

@nrwl/next:server with customServerTarget does not seem to work with typescript libs in monorepo #12032

Closed
jguze opened this issue Sep 15, 2022 · 10 comments
Assignees
Labels
outdated scope: nextjs Issues related to NextJS support for Nx stale type: bug

Comments

@jguze
Copy link

jguze commented Sep 15, 2022

Current Behavior

I'm trying to integrate a custom server into my existing nextjs app in a monorepo with multiple libs.
I ran the generator nx generate @nrwl/next:custom-server to create the custom server and project.json scaffolding.

However, every time I try to serve it in development mode with nx serve, which uses @nrwl/next:server, I'm met with the following:

error - ../../libs/shared/<lib_name>/src/index.ts
Module parse failed: Unexpected token (2:7)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
| export {
>   type MyExportedType,
|   myExportedFunction,
[ ready ] on http://localhost:4200

It seems like whatever webpack config is used under the hood isn't properly transpiling my typescript files when I use a customServerTarget.

If I remove the target and just build as normal, everything works fine.

My hunch is there's a disconnect in the code path between when you want to also build a custom server. It's apparent from the code that it branches here, and it looks like the custom server portion does much less heavy lifting.

If this is expected, it would really help to have more documentation to understand exactly how to handle this scenario when you have ts libs.

Expected Behavior

I expect the custom server to start up successfully with the same webpack config used in the normal dev server, with no typescript issues. OR some extra documentation on how to exactly use the customServerTarget option.

Steps to Reproduce

  1. Create an nx monorepo with a nextjs app created with the next generator, and a typescript lib in the monorepo.
  2. Use the typescript lib in your app
  3. Run nx generate @nrwl/next:custom-server <app-name> to add a custom server into your app
  4. Run nx serve

You will see a log similar to the following:

error - ../../libs/shared/<lib_name>/src/index.ts
Module parse failed: Unexpected token (2:7)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
| export {
>   type MyExportedType,
|   myExportedFunction,
[ ready ] on http://localhost:4200

Failure Logs

error - ../../libs/shared/<lib_name>/src/index.ts
Module parse failed: Unexpected token (2:7)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
| export {
>   type MyExportedType,
|   myExportedFunction,
[ ready ] on http://localhost:4200

Environment

 npx nx report
 >  NX   Report complete - copy this into the issue template

   Node : 16.17.0
   OS   : darwin arm64
   npm  : 8.15.0
   
   nx : 14.7.5
   @nrwl/angular : Not Found
   @nrwl/cypress : 14.7.5
   @nrwl/detox : Not Found
   @nrwl/devkit : 14.7.5
   @nrwl/eslint-plugin-nx : 14.7.5
   @nrwl/express : Not Found
   @nrwl/jest : 14.7.5
   @nrwl/js : 14.7.5
   @nrwl/linter : 14.7.5
   @nrwl/nest : Not Found
   @nrwl/next : 14.7.5
   @nrwl/node : Not Found
   @nrwl/nx-cloud : Not Found
   @nrwl/nx-plugin : Not Found
   @nrwl/react : 14.7.5
   @nrwl/react-native : Not Found
   @nrwl/schematics : Not Found
   @nrwl/storybook : 14.7.5
   @nrwl/web : 14.7.5
   @nrwl/workspace : 14.7.5
   typescript : 4.6.4
   ---------------------------------------
   Local workspace plugins:
   ---------------------------------------
   Community plugins:
@jguze jguze changed the title nx:serve with customServerTarget does not seem to work with typescript libs in monorepo @nrwl/next:server with customServerTarget does not seem to work with typescript libs in monorepo Sep 15, 2022
@wachidmudi
Copy link

wachidmudi commented Sep 23, 2022

I believe it related to this #11858, try changing the server/main.ts like in the pull request.

@FrozenPandaz FrozenPandaz added the scope: nextjs Issues related to NextJS support for Nx label Sep 23, 2022
@jaysoo jaysoo self-assigned this Oct 18, 2022
@un33k
Copy link

un33k commented Nov 30, 2022

Till @jaysoo rolls out something permanent, here is a quick change to get those who are blocked moving forward. It works for the dev server (watch) as well as the production builds.

If you have not changed the next.config.js in your nextjs app, just replace it with the following. If you have changed it, then merge the two.

Hope this helps to unblock those who need a nextjs custom server for enabling express, apolloServer, wsServer etc.

//@ts-check
const path = require('path');

// eslint-disable-next-line @typescript-eslint/no-var-requires
const { withNx } = require('@nrwl/next/plugins/with-nx');

// supported loaders
const supportedLoaders = ['next-babel-loader', 'next-swc-loader'];

// paths outside next we want to include and watch
const externalPaths = [path.join(__dirname, '../..', 'libs')];

/**
 * Checks if module rule has supported loader
 * @param rule module rule
 * @returns true if rule has a supported loader
 */
const hasNextSupportedLoader = (rule) => {
  if (Array.isArray(rule.use)) {
    return rule.use.find((l) => supportedLoaders.includes(l?.loader));
  }

  return supportedLoaders.includes(rule.use?.loader);
};

/**
 * Includes external module if they have supported loader
 * @param rule module rule
 */
const appendExternalPaths = (rule) => {
  const pattern = String(rule.test);

  if ((pattern && pattern.includes('tsx|ts')) || pattern.includes('ts|tsx')) {
    if (hasNextSupportedLoader(rule)) {
      rule.include = [...(rule?.include || []), ...externalPaths];
    }
  }
};

/**
 * @type {import('@nrwl/next/plugins/with-nx').WithNxOptions}
 **/
const nextConfig = {
  nx: {
    // Set this to true if you would like to to use SVGR
    // See: https://github.com/gregberge/svgr
    svgr: false,
  },
  reactStrictMode: true,
  webpack: (config) => {
    config.module.rules.forEach((rule) => {
      if (rule.test) {
        appendExternalPaths(rule);
      } else if (rule.oneOf) {
        rule.oneOf.forEach((rule) => {
          if (rule.test) {
            appendExternalPaths(rule);
          }
        });
      }
    });
    return config;
  },
};

module.exports = withNx(nextConfig);

@olafkrawczyk
Copy link

@un33k thx for the snippet. It helped me import libs in custom server pages. I'm having an issue tho with using libs in the custom server files for example main.ts. I get TS error
File '/.../apps/libs/util/my-lib/src/lib/index.ts' is not under 'rootDir' 'apps/my-next-app'. 'rootDir' is expected to contain all source files.
Maybe you have some ideas for some workaround?

@lukas-henry
Copy link

Just add transpilePackages to your next.config.js file


// eslint-disable-next-line @typescript-eslint/no-var-requires
const { withNx } = require('@nrwl/next/plugins/with-nx');
/**
 * @type {import('@nrwl/next/plugins/with-nx').WithNxOptions}
 **/
const nextConfig = {
  transpilePackages: ['@your-awesome-lib'], <---- IMPORTANT LINE
  nx: {
    // Set this to true if you would like to to use SVGR
    // See: https://github.com/gregberge/svgr
    svgr: false,
  },
};

module.exports = withNx(nextConfig);

To use transpilePackages you need the Next version up to 13.1.0

@kenleytomlin
Copy link

@un33k thx for the snippet. It helped me import libs in custom server pages. I'm having an issue tho with using libs in the custom server files for example main.ts. I get TS error File '/.../apps/libs/util/my-lib/src/lib/index.ts' is not under 'rootDir' 'apps/my-next-app'. 'rootDir' is expected to contain all source files. Maybe you have some ideas for some workaround?

@olafkrawczyk I'm having exactly the same issue. Have you found a solution?

@nsmith7989
Copy link
Contributor

@un33k thx for the snippet. It helped me import libs in custom server pages. I'm having an issue tho with using libs in the custom server files for example main.ts. I get TS error File '/.../apps/libs/util/my-lib/src/lib/index.ts' is not under 'rootDir' 'apps/my-next-app'. 'rootDir' is expected to contain all source files. Maybe you have some ideas for some workaround?

@olafkrawczyk @kenleytomlin I was facing this blocker as well.

My solution was to switch executors on build-custom-server to @nx/webpack:webpack rather than the default @nx/js:tsc when you add a custom server. Important to add "target": "node" for this executor

An example config that works for me. My app is called next-app

"build-custom-server": {
      "executor": "@nx/webpack:webpack",
      "defaultConfiguration": "production",
      "options": {
        "outputPath": "dist/packages/next-app",
        "main": "packages/next-app/server/main.ts",
        "tsConfig": "packages/next-app/tsconfig.server.json",
        "compiler": "swc",
        "target": "node",
        "deleteOutputPath": false,
        "generatePackageJson": true,
        "assets": []
      },
      "configurations": {
        "development": {
          "outputPath": "packages/next-app/tmp"
        },
        "production": {}
      }
    },

@olafkrawczyk
Copy link

@nsmith7989 thanks for the update, will try it!

@prkkhan1
Copy link

prkkhan1 commented Aug 4, 2023

HI @olafkrawczyk did that resolved your issue . I am facing the same issue in our mono repo app.

@olafkrawczyk

Copy link

github-actions bot commented Feb 1, 2024

This issue has been automatically marked as stale because it hasn't had any recent activity. It will be closed in 14 days if no further activity occurs.
If we missed this issue please reply to keep it active.
Thanks for being a part of the Nx community! 🙏

Copy link

This issue has been closed for more than 30 days. If this issue is still occuring, please open a new issue with more recent context.

@github-actions github-actions bot locked as resolved and limited conversation to collaborators Mar 18, 2024
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
outdated scope: nextjs Issues related to NextJS support for Nx stale type: bug
Projects
None yet
Development

Successfully merging a pull request may close this issue.

10 participants