Search code examples
vue.jsrollupjsviteesbuild

Vite production build errors: `...is not a constructor' for node_modules


I'm trying to do a build for a simple Vue-based project with Vite, but I am running into an error when actually processing the build.

My vite.config.js file:

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import nodePolyfills from 'rollup-plugin-node-polyfills'
import commonjs from '@rollup/plugin-commonjs'

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [
    vue(),
    nodePolyfills(),
    commonjs(),
  ],

  resolve: {
    alias: [
      {
        // this is required for the SCSS modules
        find: /^~(.*)$/,
        replacement: '$1',
      },
    ],
  },

  build: {
    outDir: './dist',
  },
})

The build command vite build runs fine without warnings and compiles these files in the dist folder:

  • dist/index.html
  • dist/assets/index.83eff058.js
  • dist/assets/index.acd5fd56.css
  • dist/assets/vendor.96c4e7e1.js (the problem file)

And when serving my built project, I get this error that crashes the entire thing and doesn't load anything besides CSS:

Uncaught TypeError: Vg is not a constructor
    XA http://localhost:5000/assets/vendor.96c4e7e1.js:5
    <anonymous> http://localhost:5000/assets/vendor.96c4e7e1.js:5
vendor.96c4e7e1.js:5:11738
    XA http://localhost:5000/assets/vendor.96c4e7e1.js:5
    <anonymous> http://localhost:5000/assets/vendor.96c4e7e1.js:5
    InnerModuleEvaluation self-hosted:2388
    InnerModuleEvaluation self-hosted:2388
    evaluation self-hosted:2349

I've read through the Vite and Rollup documentation and really can't figure out what to even look for. Is this occurring because of the lack of Babel, or is this something else?


Solution

  • If you are running Vite v3, you should look at this comment by sapphi-red:

    It seems it's related to @rollup/plugin-commonjs v22.

    For a workaround, use Esbuild Deps Optimization at Build Time. Set optimizeDeps.disabled = false and build.commonjsOptions.include = [].

    Here's a config that implements the workaround he mentioned:

    import { defineConfig } from 'vite'
    import react from '@vitejs/plugin-react'
    
    // https://vitejs.dev/config/
    export default defineConfig({
      plugins: [react()],
      build: {
        commonjsOptions: { include: [] },
      },
      optimizeDeps: {
        disabled: false,
      },
    });