在Next.js项目中从外部模块导入TypeScript文件时出错

ocebsuys  于 12个月前  发布在  TypeScript
关注(0)|答案(1)|浏览(146)

我在Next.js项目中遇到了一个问题,我的项目结构如下:

├── modules/
│   └── auth/
│       ├── index.ts
│       ├── page.tsx
│       └── package.json
└── nextjs-project/
    ├── ...
    └── package.json

在我的Next.js项目中,我有一个tsconfig.json文件如下:

{
  "compilerOptions": {
    "target": "esnext",
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": true,
    "skipLibCheck": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noEmit": true,
    "esModuleInterop": true,
    "module": "esnext",
    "moduleResolution": "bundler",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "jsx": "preserve",
    "incremental": true,
    "plugins": [
      {
        "name": "next"
      }
    ],
    "paths": {
      "@/*": ["./src/*"],
      "my-auth-module": ["../modules/auth/*"]
    }
  },
  "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
  "exclude": ["node_modules"]
}

在我的模块(例如auth)中,我没有配置任何webpack加载器。然而,当我尝试从Next.js项目中的auth模块导入页面时,我遇到了以下错误:

Module parse failed: Unexpected token (1:24)
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
> import NextAuth, { type NextAuthOptions } from "next-auth";

有没有一种方法可以加载.ts/.tsx文件,而不必在每次更改modules文件夹时重新构建它们?

8tntrjer

8tntrjer1#

我也遇到了同样的问题,我想我找到了解决办法:你需要使用下一个配置transpilePackages
在您的情况下,nextjs-project/next.config.js中的以下内容应该可以做到这一点:

/** @type {import('next').NextConfig} */
const nextConfig = {
  transpilePackages: ['my-auth-module'], // 👈 

  /* the rest of your config ... */
}

module.exports = nextConfig

默认情况下,Next不会编译和/或捆绑依赖项,您必须在下一个配置中显式列出它们。

相关问题