You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

pnpm工作区NestJS导入int-api-types模块报错求助

pnpm工作区中NestJS导入本地模块时路径重复拼接导致MODULE_NOT_FOUND问题

在pnpm工作区的NestJS应用中导入int-api-types模块时,Webpack编译成功、IDE无报错,但运行时出现模块找不到异常,错误路径存在重复拼接的情况。

导入代码

import { deviceController } from 'int-api-types/src/controller/device/device';

Webpack输出结果

module.exports = require("int-api-types/src/controller/device/device");

错误信息

Error: Cannot find module 'C:\programs\PyScripts\apps\server\node_modules\int-api-types\src\controller\device\devicesrc\controller\device\device\src\controller\device\device.ts'
    at createEsmNotFoundErr (node:internal/modules/cjs/loader:1430:15)
    at finalizeEsmResolution (node:internal/modules/cjs/loader:1419:15)
    at resolveExports (node:internal/modules/cjs/loader:653:14)
    at Function._findPath (node:internal/modules/cjs/loader:742:31)
    at Function._resolveFilename (node:internal/modules/cjs/loader:1380:27)
    at defaultResolveImpl (node:internal/modules/cjs/loader:1050:19)
    at resolveForCJSWithHooks (node:internal/modules/cjs/loader:1055:22)
    at Function._load (node:internal/modules/cjs/loader:1204:37)
    at TracingChannel.traceSync (node:diagnostics_channel:322:14)
    at wrapModuleLoad (node:internal/modules/cjs/loader:234:24) {
  code: 'MODULE_NOT_FOUND',
  path: 'C:\\programs\\PyScripts\\apps\\server\\node_modules\\int-api-types'
}

相关配置文件

Webpack配置

const nodeExternals = require('webpack-node-externals');
const { RunScriptWebpackPlugin } = require('run-script-webpack-plugin');
const path = require('path');

module.exports = function (options, webpack) {
    return {
        ...options,
        entry: ['webpack/hot/poll?100', options.entry],
        externals: [
            nodeExternals({
                allowlist: ['webpack/hot/poll?100'],
            }),
        ],
        plugins: [
            ...options.plugins,
            new webpack.HotModuleReplacementPlugin(),
            new webpack.WatchIgnorePlugin({
                paths: [/\.js$/, /\.d\.ts$/],
            }),
            new RunScriptWebpackPlugin({
                name: options.output.filename,
                autoRestart: false,
            }),
        ],
        resolve: {
            symlinks: false,
            extensions: ['.ts', '.json', '...'],
            alias: {
                '@': path.resolve(__dirname, './src/'),
            },
        },
    };
};

项目tsconfig.json

{
  "extends": "./../../tsconfig.json",
  "compilerOptions": {
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "outDir": "./dist",
    "baseUrl": "./",
    "resolveJsonModule": true,
    "experimentalDecorators": true,
    "strictNullChecks": false,
    "removeComments": true,
    "target": "ES2021",
    "paths": {
      "@/*": [
        "./src/*"
      ]
    }
  },
  "include": ["src", "swagger", "package.json"]
}

根目录tsconfig.json

{
    "compilerOptions": {
        "esModuleInterop": true,
        "forceConsistentCasingInFileNames": true,
        "skipLibCheck": true,
        "composite": true,
        "lib": ["es2020"],
        "module": "ES2022",
        "moduleResolution": "bundler",
        "target": "es2022",
        "isolatedModules": true,
        "moduleDetection": "force",
        "resolveJsonModule": true,
        "declaration": true,

        /* Linting */
        "strict": true,
        "noUnusedLocals": true,
        "noUnusedParameters": true,
        "noFallthroughCasesInSwitch": true,
        "noUncheckedSideEffectImports": true,
    },
}

int-api-types模块的package.json

{
    "name": "int-api-types",
    "version": "1.0.0",
    "type": "module",
    "keywords": [],
    "author": "",
    "license": "ISC",
    "description": "",
    "devDependencies": {
        "@types/node": "^22.10.1",
        "typescript": "^5.7.2"
    },
    "exports": {
        "./*": "./**/*.ts"
    },
    "peerDependencies": {
        "@nestjs/common": "^10.0.0",
        "@nestjs/swagger": "^11.0.3"
    }
}

已尝试的解决方法

  • 删除pnpm-lock.yaml和node_modules重新安装
  • 切换resolve.symlinks配置(true/false)
  • 添加模块别名

解决方案

1. 修复int-api-types的exports配置

当前exports中的./**/*.ts会触发路径解析时的重复拼接问题,改为精准的相对路径映射:

{
  "exports": {
    "./src/*": "./src/*"
  }
}

如果模块有统一入口文件(比如src/index.ts导出所有类型),可以补充主入口配置,简化导入:

{
  "main": "./src/index.ts",
  "exports": {
    ".": "./src/index.ts",
    "./src/*": "./src/*"
  }
}

2. 调整Webpack的externals配置

webpack-node-externals默认会把所有node_modules模块排除在打包之外,导致本地工作区模块的路径无法被Webpack正确处理。修改allowlist,将int-api-types纳入打包范围:

externals: [
  nodeExternals({
    allowlist: ['webpack/hot/poll?100', /^int-api-types/],
  }),
],

3. 统一模块解析方式

根目录tsconfig.json使用moduleResolution: "bundler",而项目配置用node,导致解析逻辑不一致。将项目的moduleResolution改为bundler,保持与根配置统一:

{
  "compilerOptions": {
    "moduleResolution": "bundler",
    // 其他配置...
  }
}

4. 优化导入路径

如果int-api-types有入口文件,直接导入模块名即可,避免深层路径导入:

import { deviceController } from 'int-api-types';

内容的提问来源于stack exchange,提问作者Flip0

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 17:04:53