Steps for importing Typescript-exporting libraries in next.js

Encountering a challenge while attempting to import a component from a private library that exports Typescript, we are met with the following error message:

Module parse failed: Unexpected token (82: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
| 
| // Types
> export type {

How can this issue be resolved? Attempts were made to explicitly include the library's node modules in the tsconfig file:

  "include": [
    "next-env.d.ts",
    "**/*.ts",
    "**/*.tsx",
    "node_modules/@private-lib/*.*"
  ],
  "exclude": [""]

However, these efforts proved unsuccessful. It appears that altering the webpack configuration of next.js might be a potential solution, but simply adding a Typescript loader did not yield positive results:

module.exports = {
  webpack: (config, options) => {
    config.module.rules.push({
      test: /\.(ts|js)x?$/,
      use: [
        options.defaultLoaders.babel,
        {
          loader: "ts-loader",
          options: {
            transpileOnly: true,
            experimentalWatchApi: true,
            onlyCompileBundledFiles: true,
          },
        },
      ],
    });

    return config;
  },
};

The above setup leads to the following error:

./node_modules/process/browser.js
TypeError: /home/blub/bla/website/node_modules/process/browser.js: Property left of AssignmentExpression expected node to be of a type ["LVal"] but instead got "BooleanLiteral"

If anyone has encountered similar challenges and could provide guidance on how to proceed, it would be greatly appreciated. The intricacies of this situation have proven daunting, and assistance is much needed.

Answer №1

This question may have been asked a while ago, but I wanted to provide an updated response to build upon the original answer by directed-laugh for anyone who comes across this issue.

It appears that transpiling modules through next.config.js is the recommended solution. With the release of NextJS 13.1, there is no longer a need for installing the extra next-transpile-modules package as these functionalities are now built into NextJS 13.1.

To implement this in your next.config.js, simply add the transpilePackages option and specify the name of your ts package.

module.exports = {
  ...
  transpilePackages: ['my-ts-package'],
}

For more information, you can refer to the Module Transpilation documentation on the NextJS website.

Answer №2

When I stumbled upon this Stack Overflow question, it resonated with me as I faced a similar issue in my next.js project with TypeScript (

yarn create next-app --typescript
).

  • yarn: 1.22.17
  • next: 12.0.7
  • node: 14.18.1

The problem arose after including an external ts package within a tsx file internally in the project. It seemed like there was some transpiling magic happening behind the scenes, trying to interpret the ts file as JavaScript.

To resolve this issue, I turned to next-transpile-modules (^9.0.0). Here are the steps that worked for me:

  1. If your next.config.js starts like this
/** @type {import('next').NextConfig} */

module.exports = {
  reactStrictMode: true,
  env: {
  },
}

  1. And you have an external TS library private-lib causing a compile-time error when importing from a tsx file,

Follow these steps:

  1. yarn add next-transpile-modules
  2. yarn add file:/path/to/private-lib
  3. Adjust the import statements in ts/tsx files for private-lib
  4. Update next.config.js as shown below
/** @type {import('next').NextConfig} */
// see https://github.com/martpie/next-transpile-modules#readme
const withTM = require('next-transpile-modules')(['private-lib']);

module.exports = withTM({
  reactStrictMode: true,
  env: {
  },
})

Your mileage may vary, but hopefully, this helps! #FixMagicWithMoreMagic

Answer №3

It seems like the issue stems from transpiling jsx? files using ts-loader. To resolve this, it would be best to only transpile tsx? files if ts-loadder is being used:

webpack: (config, options) => {
  config.module.rules.push({
    test: /\.(ts)x?$/, // Transpile only `tsx?` files
    use: [
      // options.defaultLoaders.babel - This loader may not be necessary
      {
        loader: "ts-loader",
        options: {
          transpileOnly: true,
          experimentalWatchApi: true,
          onlyCompileBundledFiles: true,
        },
      },
    ],
  });

  return config;
},

Additionally, if your repository currently includes jsx? files that import tsx? files, you may need to set { "allowJs": true } in your tsconfig.json.

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

Mixing TypeScript generic types loosely

Let's explore a simple example of typescript mixins: import { Observable, of } from 'rxjs'; class Service<TDataType> { public foo(f: TDataType): Observable<TDataType> { return of(f); } } type GConstructor<T = {}> = new ...

What is the best way to resolve the "unknown" type using AxiosError?

I'm currently working on developing a customized hook for axios, but I've encountered the following error: Argument of type 'unknown' is not assignable to parameter of type 'SetStateAction<AxiosError<unknown, any> | unde ...

What is preventing me from adding members to an imported declaration?

Currently, I am attempting to include a constructor in an imported declaration. As per the information provided in the documentation, this should be feasible. (Refer to Chapter Adding using an interface) Below is the code snippet that I have used: import ...

Formatting database values in `where` conditions for strings in TypeORM: A simple guide

I am trying to utilize TypeORM's "exist" method in order to check if a name has already been inserted into the database. My issue is that I cannot determine whether the name was inserted in uppercase or lowercase, leading to potential false validatio ...

Styling array of arrays

When retrieving data from an API, the structure looks like this: "key1" : { "subkey1" : value "subkey2" : value "subkey3" : value } "key2" : { &q ...

The error occurred in Commands.ts for Cypress, stating that the argument '"login"' cannot be assigned to the parameter of type 'keyof Chainable<any>))`

Attempting to simplify repetitive actions by utilizing commands.ts, such as requesting email and password. However, upon trying to implement this, I encounter an error for the login (Argument of type '"login"' is not assignable to parameter of t ...

Retrieve values from DynamoDB in their original Number or String formats directly

Here is the code I am using to retrieve data from DynamoDB. async fetchData(params: QueryParams) { return await this.docClient.send(new QueryCommand(params)); } const dbObject: QueryParams = { TableName: process.env.TABLE_NAME, KeyCo ...

Generating distinct identifiers for WebSocket and net.Socket connections

I am looking to assign unique identifiers to Websockets and net.Sockets so that each client can be identified by the identifier attached to the socket when a message is received. Previous findings: For WebSocket: Based on my research on Stack Overflow a ...

What steps should I take to choose esNext from the typescript menu within visual studio 2017?

When utilizing dynamic import with TypeScript in Visual Studio 2017, I encountered the following error: TS1323(TS) Dynamic imports are only supported when the '--module' flag is set to 'commonjs' or 'esNext'. I attempted to c ...

Leveraging parameters within a sequence of object properties

Within the realm of Angular, I am dealing with interfaces that take on a structure similar to this (please note that this code is not my own): export interface Vehicles { id: number; cars: Car; trucks: Truck; } Export interface Car { make: ...

Looking for assistance in integrating custom data into session.user object with next-auth

I am having trouble adding custom data to the session.user object and it is not working as expected. What's strange is that when I send this: const user = { id: '1', name: "J Smith", email: "<a href="/cdn-cgi/l/email-protection" class="__ ...

Develop a TypeScript class by incorporating a static function from an external library, while ensuring type safety

I am looking to enhance the capabilities of the rxjs5 Observable class by adding a static function. While this can be easily accomplished in plain JavaScript: var myStaticFn = function() { /* ... */ }; Observable.myStaticFn = myStaticFn; this approach w ...

Is it possible to declare an object literal with optional keys in a Typescript function signature?

I have a .d.ts file similar to this: declare function myfunc(): { something: (err, { req, res, errorInfo, query, pathname, extra }?) => void; }; This declaration states that the function takes two arguments, with the second argument being an optional ...

What could be causing the error message "Error: Error serializing ___ returned from getStaticProps" to appear?

When I make a call inside getStaticProps, I keep encountering the error below and I'm struggling to understand why: Error: Error serializing `.lingo` returned from `getStaticProps` in "/". Reason: `undefined` cannot be serialized as JSON. T ...

Adding TypeScript definition file to an npm package: A step-by-step guide

Is it possible to include typescript definitions (.d.ts files) in a pure javascript project without using TypeScript itself? I'm struggling to find any information on how to do this directly in the package.json. ...

Is it possible to integrate Storybook within the same domain as your website?

Is there a method to display the static index.html created when storybook is built from NextJS? The static Storybook site is constructed in ~/build/storybook/.... I am hoping to use NextJS to direct to that file like so. http://mysite/storybook What wo ...

Encountered an HttpErrorResponse while trying to access the API endpoint

I am encountering an issue when trying to update and insert data with a single post request. https://i.sstatic.net/T9UKR.png Below is my API code: https://i.sstatic.net/kkwqs.png Here is the service code: https://i.sstatic.net/IUMSd.png This section ...

The error [next-auth][error][CLIENT_FETCH_ERROR] occurs due to an unexpected token '<', "<!DOCTYPE" in the response which is not valid JSON

Whenever I click on the Google login button, it redirects me to /api/auth/error. I am using Next.js version 14. Here is my nextauth.js file: import NextAuth from "next-auth"; import GoogleProvider from "next-auth/providers/google"; imp ...

Problem with selecting dates in rangepicker

Having trouble with my recursion code for selecting dates in a rangepicker: recurse( () => cy.get('.mantine-DatePicker-yearsListCell').invoke('text'), (n) => { if (!n.includes(year)) { //if year not f ...

Error: The default export is not a component compatible with React in the specified page: "/"

I'm facing an issue while building my next app. Despite using export default, I keep encountering an error that others have mentioned as well. My aim is to create a wrapper for my pages in order to incorporate elements like navigation and footer. vi ...