Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load libraries which export Typescript in next.js

When trying to import a component from a private library which exports Typescript, we get 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 could I fix that? I tried to explicitly include the libraries node modules in the tsconfig file:

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

but unfortunately, to no avail. There seems to be the possibility to change the webpack configuration of next.js, but trying to just shove in a Typescript loader did not work, unfortunately:

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;
  },
};

It produces this 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"

So is anybody out there who also faced this problem and could point me into the right direction? There seems to be a lot of magic at work here and I am kind of lost.

like image 317
Gh05d Avatar asked Sep 13 '25 15:09

Gh05d


1 Answers

This question is kind of old, so I thought I'd post an update to extend on directed-laugh's original answer for anyone who stumbles across this issue.

As mentioned, transpiling the modules via next.config.js seems to be the solution. Though with NextJS 13.1 there is no need to install the additional next-transpile-modules package as these features are available natively in NextJS 13.1.

In next.config.js, just add the transpilePackages option and include the name of the ts package.

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

See Module Transpilation

like image 120
Jaxon Crosmas Avatar answered Sep 15 '25 04:09

Jaxon Crosmas