简体   繁体   中英

Module not found with corresponding type declarations using Typescript with Next.js

I have a next.js project that I am trying to add typescript to.

My folder structure is as follows:

api
  aggregation.ts
interfaces
  index.ts
components
  Component1
    index.js
    index.module.css
  Component2
    index.js
    index.module.css
pages
  page1
    index.js
    index.module.css

I have an alias for interfaces in next.config.js

config.resolve.alias.interfaces = path.join(__dirname, 'interfaces');

Now the actual issue

index.ts in interfaces exports interfaces such as

 export interface Order {
  store: Store;
  orderNumber: string;
  totals: Totals;
  customer: Customer;
  currency: Currency;
  paymentMethod: PaymentMethod;
  items: OrderProduct[];
  createdAt: string;
  orderId: string;
}

And I'm trying to import them into aggregation.ts like

import { Order } from 'interfaces';

And am getting

Cannot find module 'interfaces' or its corresponding type declarations.

Which is also causing the builds to fail.

I have installed

"@types/node": "^16.0.1",
"@types/react": "^17.0.14",
"typescript": "^4.3.5",

And next has generated next-env.d.ts correctly with

/// <reference types="next" />
/// <reference types="next/types/global" />

Any ideas on how to fix the Cannot find module issue? I have a feeling it may have something to do with my folder structure or my build step. But I am also getting syntax highlighting indicating the import errors so it is probable typescript config related.

Any advice would be appreciated!

You can configure module aliases in your tsconfig.json using the baseUrl option to import directly from the root (and also use the paths option for further aliases configuration).

// tsconfig.json
{
    "compilerOptions": {
        "baseUrl": "."
    }
}

Allowing you to use the following import.

import { Order } from 'interfaces';

From the Absolute Imports and Module path aliases documentation:

Next.js automatically supports the tsconfig.json and jsconfig.json "paths" and "baseUrl" options since Next.js 9.4.

These options allow you to configure module aliases, for example a common pattern is aliasing certain directories to use absolute paths.

One useful feature of these options is that they integrate automatically into certain editors, for example VSCode.

The baseUrl configuration option allows you to import directly from the root of the project.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM