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

使用Webpack构建NestJS时出现找不到cookie-parser模块错误

运行Webpack构建后的NestJS应用时出现以下错误:

Error: Cannot find module 'cookie-parser'

已通过npm安装cookie-parser且它在package.json中列为依赖项,不使用Webpack时应用运行正常。以下是我的Webpack配置:

const path = require('path');
const { IgnorePlugin } = require('webpack');
const {
  swcDefaultsFactory,
} = require('@nestjs/cli/lib/compiler/defaults/swc-defaults');
const TsconfigPathsPlugin = require('tsconfig-paths-webpack-plugin');
const Dotenv = require('dotenv-webpack');
const CopyPlugin = require("copy-webpack-plugin");


dotenv.config();


/** @type { import('webpack').Configuration } */
module.exports = {
  entry: './src/main',
  externals: {},
  module: {
    rules: [
      {
        exclude: /node_modules/,
        test: /\.ts$/,
        use: {
          loader: 'swc-loader',
          options: swcDefaultsFactory().swcOptions,
        },
      },
    ],
  },
  node: {
    __dirname: false,
    __filename: false,
  },
  output: {
    filename: '[name].js',
    path: path.resolve(__dirname, 'dist/'),
  },
  plugins: [
    new Dotenv(),
    new CopyWebpackPlugin({
        patterns: [
            './node_modules/cookie-parser/index.js',
            './node_modules/@nestjs/swagger/dist/swagger-ui-dist/swagger-ui.css',
            './node_modules/@nestjs/swagger/dist/swagger-ui-dist/swagger-ui.js',
            './node_modules/@nestjs/swagger/dist/swagger-ui-dist/swagger-ui-standalone-preset.js',
            './node_modules/swagger-ui-dist/favicon-16x16.png',
            './node_modules/swagger-ui-dist/favicon-32x32.png'
        ]
    }),
    new IgnorePlugin({
      checkResource(resource) {
        const lazyImports = [
            '@fastify/static',
            '@fastify/view',
            '@nestjs/microservices',
            '@nestjs/microservices/microservices-module',
            '@nestjs/platform-express',
            '@nestjs/websockets/socket-module',
            'amqp-connection-manager',
            'amqplib',
            'cache-manager',
            'cache-manager/package.json',
            'class-transformer/storage',
            'hbs',
            'ioredis',
            'kafkajs',
            'mqtt',
            'nats',
            'compression',
          ];
        if (!lazyImports.includes(resource)) {
          return false;
        }
        try {
          require.resolve(resource, { paths: [process.cwd()] });
        } catch (err) {
          return true;
        }
        return false;
      },
    }),
  ],
  resolve: {
    extensions: ['.js', '.json', '.ts'],
    mainFields: ['main'],
    plugins: [new TsconfigPathsPlugin({ configFile: 'tsconfig.json' })],
  },
  target: 'node',
};

原因分析

  1. 模块复制不完整:当前仅通过CopyPlugin复制了cookie-parser的入口文件index.js,但该模块的核心逻辑在lib/目录下,单独复制入口文件无法满足模块完整加载的需求。
  2. 模块解析路径不匹配:Webpack构建后,运行时的模块解析路径与开发环境不同,单独复制的文件无法被Node.js的require正确识别为合法模块。

解决办法

方法一:让Webpack自动打包cookie-parser(推荐)

无需手动复制模块,直接让Webpack分析依赖并打包:

  • 移除CopyPlugin中./node_modules/cookie-parser/index.js这一行配置;
  • 保持externals为空(当前配置已满足),Webpack会自动将cookie-parser打包进最终产物。

方法二:完整复制cookie-parser模块目录

如果必须保留复制方式,需复制整个模块目录以保证结构完整:
修改CopyPlugin的patterns配置:

new CopyWebpackPlugin({
    patterns: [
        { from: './node_modules/cookie-parser', to: './node_modules/cookie-parser' },
        // 其他swagger相关文件保持不变
        './node_modules/@nestjs/swagger/dist/swagger-ui-dist/swagger-ui.css',
        './node_modules/@nestjs/swagger/dist/swagger-ui-dist/swagger-ui.js',
        './node_modules/@nestjs/swagger/dist/swagger-ui-dist/swagger-ui-standalone-preset.js',
        './node_modules/swagger-ui-dist/favicon-16x16.png',
        './node_modules/swagger-ui-dist/favicon-32x32.png'
    ]
}),

同时确保运行时dist/node_modules能被Node.js识别,或通过设置NODE_PATH=./dist/node_modules调整模块解析路径。

方法三:将cookie-parser设为外部依赖

如果不想打包该模块,希望运行时从项目根目录的node_modules加载,可添加到externals:

externals: {
    'cookie-parser': 'commonjs cookie-parser'
},

这种方式需保证运行环境中已安装cookie-parser依赖,适合生产环境单独管理依赖的场景。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 08:30:57