NextJS: Can't use absolute imports in external libraries when using experimental.externalDir

Viewed 771

Having the following folder structure of my monorepo that uses nextjs, lerna and npm workspaces:

packages
    next-js-app
        pages
            index.tsx
        tsconfig.json
    ui-library
        src
            components
                 dropdown.tsx
            index.ts
            utils.ts
        tsconfig.json
package.json
lerna.json
tsconfig.json

I want to import the ui-library in the next-js-app such as:

// packages/next-js-app/pages/index.tsx
import { UiLibrary } from '@workspaceName/ui-library'

I allowed it by adding externalDir: true to experimental key in the next.config.js inside the next-js-app:

module.exports = {
  ...
  experimental: {
    externalDir: true
  }
  ...
}

Problem

The import works, but inside the packages/ui-library/src/components/dropdown.tsx there's a line:

// packages/ui-library/src/components/dropdown.tsx
import { helperFunction } from 'utils'

meaning that I want to import helperFunction from packages/ui-library/src/utils.ts. When running next dev script from packages/next-js-app I get the following error:

wait  - compiling...
error - ../ui-library/src/components/dropdown.tsx:3:0
Module not found: Can't resolve 'utils'
  1 | ...
  2 | ...
> 3 | import { helperFunction } from "utils"
  4 | 
  5 | const Dropdown = () => {
  6 |   const onClick = (event) => {

While if I run the ui-library separately it will be ok with using absolute paths in imports.

Question

How can I make absolute imports work in this case?

1 Answers

The way I fixed it in my case, was adding aliases to my webpack config (inside next.config.js file)

module.exports = {
 ...
 experimental: {
   externalDir: true
 }
 config.resolve = {
  ...config.resolve,
    alias: {
      ...config.resolve.alias,
      'utils': path.resolve('../../packages/ui-library/src/utils'),
      // ^ defined all paths used within my external UI library
    },
  }
}
Related