【踩坑笔记】vite build时 Error: 'default' is not exported by ../xxx.js, imported by xxx'

2022-09-08 09:10:00

问题现象

使用vite build打包,报错

error during build:
Error: 'default' is not exported by ../cRonstrue/dist/cronstrue.js, imported by src/components/CronParser.vue?vue&type=script&setup=true&lang.ts
    at error (file:///Users//Workspace/DEV/study/awesome-cron/node_modules/rollup/dist/es/shared/rollup.js:1858:30)
    at Module.error (file:///Users//Workspace/DEV/study/awesome-cron/node_modules/rollup/dist/es/shared/rollup.js:12429:16)
    at Module.traceVariable (file:///Users//Workspace/DEV/study/awesome-cron/node_modules/rollup/dist/es/shared/rollup.js:12788:29)
    at ModuleScope.findVariable (file:///Users//Workspace/DEV/study/awesome-cron/node_modules/rollup/dist/es/shared/rollup.js:11440:39)
    at FunctionScope.findVariable (file:///Users//Workspace/DEV/study/awesome-cron/node_modules/rollup/dist/es/shared/rollup.js:6372:38)
    at ChildScope.findVariable (file:///Users//Workspace/DEV/study/awesome-cron/node_modules/rollup/dist/es/shared/rollup.js:6372:38)
    at ReturnValueScope.findVariable (file:///Users//Workspace/DEV/study/awesome-cron/node_modules/rollup/dist/es/shared/rollup.js:6372:38)
    at ChildScope.findVariable (file:///Users//Workspace/DEV/study/awesome-cron/node_modules/rollup/dist/es/shared/rollup.js:6372:38)
    at MemberExpression.bind (file:///Users//Workspace/DEV/study/awesome-cron/node_modules/rollup/dist/es/shared/rollup.js:8601:49)
    at CallExpression.bind (file:///Users//Workspace/DEV/study/awesome-cron/node_modules/rollup/dist/es/shared/rollup.js:5269:23)

问题原因

vite好像只支持ESM,cronstrue库是UMD,需要做兼容

解决方法

根据最新的3.0 官方文档 可知,需要在配置根据增加配置项

export default defineConfig({
  optimizeDeps: {
    include: ['linked-dep']
  },
  build: {
    commonjsOptions: {
      include: [/linked-dep/, /node_modules/]
    }
  }
})