版本
- vite: "^5.0.11"
解决方法
添加 optimizeDeps.disabled = false
和 build.commonjsOptions.include = []
。
vite.config.ts
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
export default defineConfig({
plugins: [react()],
build: {
commonjsOptions: { include: [] },
},
optimizeDeps: {
disabled: false,
},
});
原因分析
这个问题大概从 vite3 就开始存在了,vite 使用 rollup 进行生产构建,在循环依赖等情况下,rollup 处理 commonjs 模块出现问题。我这里是引用了 cssom 出现的, 大概是 cssom parse.js 文件末尾动态导入其他模块导致的,parse.js 顶部其他部分代码有使用结尾导入的这些模块。
// ....
//.CommonJS
exports.parse = CSSOM.parse;
// The following modules cannot be included sooner due to the mutual dependency with parse.js
CSSOM.CSSStyleSheet = require("./CSSStyleSheet").CSSStyleSheet;
CSSOM.CSSStyleRule = require("./CSSStyleRule").CSSStyleRule;
CSSOM.CSSImportRule = require("./CSSImportRule").CSSImportRule;
CSSOM.CSSGroupingRule = require("./CSSGroupingRule").CSSGroupingRule;
CSSOM.CSSMediaRule = require("./CSSMediaRule").CSSMediaRule;
CSSOM.CSSConditionRule = require("./CSSConditionRule").CSSConditionRule;
CSSOM.CSSSupportsRule = require("./CSSSupportsRule").CSSSupportsRule;
CSSOM.CSSFontFaceRule = require("./CSSFontFaceRule").CSSFontFaceRule;
CSSOM.CSSHostRule = require("./CSSHostRule").CSSHostRule;
CSSOM.CSSStyleDeclaration = require('./CSSStyleDeclaration').CSSStyleDeclaration;
CSSOM.CSSKeyframeRule = require('./CSSKeyframeRule').CSSKeyframeRule;
CSSOM.CSSKeyframesRule = require('./CSSKeyframesRule').CSSKeyframesRule;
CSSOM.CSSValueExpression = require('./CSSValueExpression').CSSValueExpression;
CSSOM.CSSDocumentRule = require('./CSSDocumentRule').CSSDocumentRule;
///CommonJS
参考资料
- https://stackoverflow.com/questions/70454977/vite-production-build-errors-is-not-a-constructor-for-node-modules
- https://github.com/vitejs/vite/issues/9703#issuecomment-1216662109