Using Vite with code splitting enabled without adding the `type="module"` attribute in script

528 Views Asked by At

I'm working on an embeddable widget for websites where clients embed the widget into their website using a script tag in the following format:

<script src="https://embed.app.com/USER_ID"></script>

This script serves the app entry which then build up the widget on the client's website.

My current setup is Webpack 4 (with Vue-cli), and I'm trying to migrate to Vite mainly for better dev experience.

Here is my config:

import { defineConfig } from 'vite';
import { createVuePlugin as vue } from 'vite-plugin-vue2';

const path = require('path');

export default defineConfig({
  plugins: [vue()],
  resolve: {
    alias: {
      '@': path.resolve(__dirname, './src/')
    }
  },
  build: {
    outDir: 'dist',
    rollupOptions: {
      output: {
      entryFileNames: 'app.js', //to prevent add a hash to filename
      chunkFileNames: '[name].js', //to prevent add a hash to filename
      assetFileNames: '[name].[ext]' //to prevent add a hash to filename
      }
    }
  },
  server: {
    host: '127.0.0.1',
    port: 8081,
    strictPort: true
  },
  css: {
    preprocessorOptions: {
      scss: {}
    }
  }
});

However, since I don't ship an index.html, and the script is loaded without type="module" (as I mentioned before), I encounter the following error in the browser:

Uncaught SyntaxError: export declarations may only appear at top level of a module.

Which is as I understand because of the fact that Vite's default output format is es which has to be loaded as a moudle.

So I attempted using the umd or iife formats, and then I get:

Invalid value "umd" for option "output.format" - UMD and IIFE output formats are not supported for code-splitting builds.

So my question is How can I use Vite with code splitting enabled but without requiring the `type attribute in the script that's loading the app?

0

There are 0 best solutions below