Turborepo internal package WITHOUT Next.js

Turborepo internal package WITHOUT Next.js

When working with TypeScript and building a monorepo, you may come across the need to create an internal package that does not depend on Next.js. In this blog post, we will explore two solutions to achieve this.

Solution 1: Using a Custom Build Script

The first solution involves creating a custom build script that compiles your TypeScript code without the Next.js dependency. Here’s how you can do it:


    // package.json
    {
      "name": "my-package",
      "scripts": {
        "build": "tsc"
      },
      "devDependencies": {
        "typescript": "^4.4.3"
      }
    }
  

In the above example, we have a simple package.json file with a build script that runs the TypeScript compiler (tsc). By specifying TypeScript as a devDependency, we ensure that it is only used during the build process and not as a runtime dependency.

Solution 2: Using Conditional Imports

The second solution involves using conditional imports to exclude the Next.js dependency when building the internal package. Here’s an example:


    // my-module.ts
    import { useRouter } from 'next/router';
    
    let router;
    
    if (process.env.IS_BUILD) {
      router = null;
    } else {
      router = useRouter();
    }
    
    export default router;
  

In the above code snippet, we import the useRouter function from the ‘next/router’ module, but we conditionally assign it to the router variable based on the value of the IS_BUILD environment variable. During the build process, we set IS_BUILD to true, which effectively excludes the Next.js dependency.

Conclusion

By following either of the two solutions mentioned above, you can create an internal package in a TypeScript monorepo without the Next.js dependency. Whether you choose to use a custom build script or conditional imports, it’s important to ensure that your package is built correctly and does not include any unnecessary dependencies.

Happy coding!


Posted

in

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *