如何解决Next.js 13中项目引用路径别名触发的Webpack错误?
问题:Next.js 13中外部项目路径别名与Project References无法正常工作
我正通过Create T3 App脚手架,将一个小型旧React项目(包含配套的NestJS服务端)迁移至Next.js 13。我在所有项目里都会频繁使用project references,本次按如下方式配置了tsconfig.json的paths别名与references:
{ "compilerOptions": { "target": "es2017", "lib": ["dom", "dom.iterable", "esnext"], "allowJs": true, "skipLibCheck": true, "strict": true, "forceConsistentCasingInFileNames": true, "noEmit": true, "esModuleInterop": true, "module": "esnext", "moduleResolution": "node", "resolveJsonModule": true, "isolatedModules": true, "jsx": "preserve", "incremental": true, "noUncheckedIndexedAccess": true, "baseUrl": ".", "paths": { "@core/*": ["../../../../libs/core/src/*"] } }, "references": [ { "path": "../../../../libs/core/" } ], "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", "**/*.cjs", "**/*.mjs"], "exclude": ["node_modules"] }
但持续触发Webpack加载器错误:
error - ../../../../libs/core/src/path/to/file.ts
Module parse failed: Unexpected token (4:12) You may need an
appropriate loader to handle this file type, currently no loaders are
configured to process this file.
该文件在VS Code中无红色错误标记,智能提示正常。我尝试在next.config.mjs中配置Webpack别名:
// @ts-check /** * Run `build` or `dev` with `SKIP_ENV_VALIDATION` to skip env validation. * This is especially useful for Docker builds. */ !process.env.SKIP_ENV_VALIDATION && (await import("./src/env/server.mjs")); import path from 'path'; /** @type {import("next").NextConfig} */ const config = { reactStrictMode: true, swcMinify: true, i18n: { locales: ["en"], defaultLocale: "en", }, webpack: (config, { buildId, dev, isServer, defaultLoaders, nextRuntime, webpack }) => { return { ...config, resolve: { ...config.resolve, alias: { ...config.resolve.alias, '@core': path.resolve('../../../../libs/core/src'), } } } }, }; export default config;
但错误没有任何变化。添加ts-loader则导致应用其他部分报错,我希望尽可能不使用Babel解决问题。如何让外部项目的路径别名在Next.js 13中正常工作?
解决方案
使用next-transpile-modules包可以让项目引用及其别名正常工作。该方案要求tsconfig.json正确设置baseUrl和paths字段,然后在next.config.mjs中做如下修改:
import transpile from 'next-transpile-modules'; const withModules = transpile([ '../../../../libs/core' ]); /** @type {import("next").NextConfig} */ const config = { // 保留你原有的配置项 reactStrictMode: true, swcMinify: true, i18n: { locales: ["en"], defaultLocale: "en", }, }; export default withModules(config);
内容的提问来源于stack exchange,提问作者his dudeness
相关产品推荐
相关产品推荐

