skip to Main Content

I’ve been learning React (kind of new to it) and I’m working on a project and I did an npm create vite@latest. So far everything works fine when I do run dev. However when I do run build, then go to the dist folder and open the index.html file I get a blank page.

So I do an inspect page in FireFox and I get these errors –

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resources at file:///assets/index-J7cny882.js. (Reason: CORS request not http)

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resources at file:///assets/index-BAXwXR6k.css. (Reason: CORS request not http)

I’m bit puzzled by this. Don’t know whats wrong or how to fix it. I did come across some things online that mentioned adding "homepage": "." to package.json. I did that but didn’t help.

I appreciate the help.

Thanks.

2

Answers


    1. Serve the dist folder using a local HTTP server
      The simplest solution is to use a local HTTP server to serve your built files. You can install one globally and use it:

    Install a simple HTTP server:

    npm install -g serve
    

    Serve your dist folder:

    serve dist
    

    This will host your project on http://localhost:3000 (or another port it provides), and you can access your project without encountering CORS issues.

    1. Adjust base in vite.config.js
      When building with Vite, ensure the paths to your assets are relative or configured correctly. By default, Vite uses / as the base, which can cause issues if your project isn’t served from a root path.

    Modify the vite.config.js file to set a relative base:

    javascript

    import { defineConfig } from 'vite'
    
    export default defineConfig({
      base: './', // Ensures relative paths for assets
    })

    Then rebuild your project:

    npm run build
    

    Now, the paths in the generated index.html file will be relative, and you can open it directly in the browser without needing a local server.

    1. Avoid opening directly with file:///
      Browsers enforce stricter security policies for files opened with file:///. Using a local HTTP server (as shown in step 1) avoids these restrictions.
    Login or Signup to reply.
  1. You need to serve the page actually. If you are using the Vite create for React you can do the following to test your build.

    // Build your project into the dist folder
    npm run build 
    // Preview your project using vite server
    npm run preview
    

    The preview command is already present on the package.json so you do not need to configure anything.

    Keep in mind you should not use this for a production deploy. It only serves as a preview utility.

    You can read the documentation here https://vite.dev/guide/cli#vite-preview

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search