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

从CRA+CRACO迁移到Vite后构建及运行报错问题求助

解决Vite构建Redux-Form时的RollupError问题

问题分析

本地开发正常,但构建时出现Rollup错误:

RollupError: node_modules/redux-form/es/structure/plain/deepEqual.js (1:7):
"default" is not exported by "node_modules/lodash/isNil.js",
imported by "node_modules/redux-form/es/structure/plain/deepEqual.js".

核心原因是redux-form采用CommonJS风格的默认导入语法(import isNil from 'lodash/isNil'),但lodash的ES模块仅导出具名函数(export function isNil(...)),没有默认导出,导致Rollup无法解析导入逻辑。

之前尝试配置build.rollupOptions.external虽然能完成构建,但会让这些模块不被打包到产物中,浏览器运行时无法识别裸模块标识符(如lodash/isNil),因此出现报错:

Uncaught TypeError: Failed to resolve module specifier "lodash/isNil". Relative references must start with either "/", "./", or "../".

解决方案

步骤1:安装Rollup CommonJS插件

该插件可将CommonJS模块转换为Rollup能识别的ES模块,修复默认导入的适配问题:

npm install @rollup/plugin-commonjs --save-dev

步骤2:修改Vite配置

在Vite配置文件中导入并添加该插件,同时移除external配置:

import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react-swc';
import path from 'path';
import { fileURLToPath } from 'url';
import commonjs from '@rollup/plugin-commonjs';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

export default defineConfig({
    plugins: [
        react(),
        // 添加CommonJS插件,处理redux-form和lodash的模块转换
        commonjs({
            include: ['node_modules/redux-form/**/*', 'node_modules/lodash/**/*'],
            defaultIsModuleExports: true
        })
    ],

    define: {
        global: 'window',
        module: 'window',
    },

    resolve: {
        alias: {
            '../../theme.config': path.resolve(__dirname, './src/semantic-ui/theme.config'),
        },
    },

    css: {
        preprocessorOptions: {
            less: {
                math: 'always',
                javascriptEnabled: true,
            },
        },
    },

    build: {
        rollupOptions: {
            // 移除之前的external配置,确保依赖被正常打包
        },
    },
});

步骤3:重新构建

执行构建命令验证是否正常完成:

npm run build

构建完成后使用serve -s dist启动,即可正常访问,不再出现模块解析错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 23:03:26