Backend Integration

If you want to serve the HTML using a traditional backend (e.g. Rails, Laravel) but use Vite for serving assets, here’s what you can do:

  1. In your Vite config, configure the entry and enable build manifest:

    1. // vite.config.js
    2. export default {
    3. build: {
    4. manifest: true,
    5. rollupOptions: {
    6. // overwrite default .html entry
    7. input: '/path/to/main.js'
    8. }
    9. }
    10. }

    Also remember to add the dynamic import polyfill to your entry, since it will no longer be auto-injected:

    1. // add the beginning of your app entry
    2. import 'vite/dynamic-import-polyfill'
  2. For development, inject the following in your server’s HTML template (substitute http://localhost:3000 with the local URL Vite is running at):

    1. <!-- if development -->
    2. <script type="module" src="http://localhost:3000/@vite/client"></script>
    3. <script type="module" src="http://localhost:3000/main.js"></script>

    Also make sure the server is configured to serve static assets in the Vite working directory, otherwise assets such as images won’t be loaded properly.

  3. For production: after running vite build, a manifest.json file will be generated alongside other asset files. You can use this file to render links with hashed filenames (note: the syntax here is for explanation only, substitute with your server templating language):

    1. <!-- if production -->
    2. <link rel="stylesheet" href="/assets/{{ manifest['index.css'].file }}" />
    3. <script type="module" src="/assets/{{ manifest['index.js'].file }}"></script>