Search code examples
vue.jscorsvuejs3vite

View a Vue website by just opening the HTML file in the browser (CORS policy error)


I have created a simple Vue3 + Vite website to present something to another person. It works fine when previewing on my side (using npm run dev or npm run build + npm run preview and then opening the browser at localhost:5173). It also works when deployed to Github Pages.

What I would like to do is to simply be able to hand over the HTML, CSS and JS files of the website to the other person and for them to be able to simply open the index.html in the browser and view the website.

Currently, when trying that with index.html (from the generated dist directory) it does not work due to the:

Access to script at 'file:///assets/index-a911f458.js' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, isolated-app, brave, https, chrome-untrusted, data, chrome-extension, chrome.

error.

I want to avoid forcing the other person to install node.js as well as dockerizing the project etc.


Solution

  • Compile all code into index.html

    This avoids those CORS errors because there's nothing to import at run-time.

    I had the same need as OP; a static index.html that can be shared and opened locally in browsers.

    By compiling all code into index.html, we avoided the same CORS errors we'd otherwise have (unavoidable CORS errors when attempting to include JS modules). FYI regular non-module JS includes still work like normal, if we wanted to have an extra .js file.

    We didn't have any media assets so we easily distributed this single index.html as-is, and people could open it locally, even offline (since we didn't connect to any remote API).

    Main caveat: Your index.html will be large, e.g. 120kb. This is because everything required to run your app is jammed into it, including any framework (e.g. Vue). You definitely want to keep minification on.

    For convenience, we did this using the Vite build plugin below. Please read about it as it has limitations.

    https://github.com/richardtallent/vite-plugin-singlefile

    vite.config.js

    plugins: [
      viteSingleFile()
    ]