Skip to content
Advertisement

Failed to load module script: Expected a JavaScript module

The error which I was facing

I am using vite as build tool for my react app and golang as backend.

I built the app for production and host the app on my http server.

my directory structure:

server
  |- dist
  |    | index.html
  |    |- assets
  |         | index.js
  |         | index.css
  | main.go

To host my files the code looks like (inside main.go)

fs := http.FileServer(http.Dir("./dist"))
http.Handle("/", fs)

in index.html

<script type="module" crossorigin src="/assets/index.fd457ca0.js"></script>
<link rel="stylesheet" href="/assets/index.bdcfd918.css">

The code did actually send correct files but with wrong headers.

my network panel in dev tools

Advertisement

Answer

So I had to write my own file server to set the headers manually like:

contentTypeMap := map[string]string{
    ".html": "text/html",
    ".css":  "text/css",
    ".js":   "application/javascript",
}

filepath.Walk("./dist", func(path string, info os.FileInfo, err error) error {
    if err != nil {
        log.Fatalf(err.Error())
    }
    if info.IsDir() {
        return err
    }

    dirPath := filepath.ToSlash(filepath.Dir(path))
    contentType := contentTypeMap[filepath.Ext(info.Name())]
    handlePath := "/" + strings.Join(strings.Split(dirPath, "/")[1:], "/")

    hf := func(w http.ResponseWriter, r *http.Request) {
        w.Header().Add("Content-Type", contentType) // <---- key part
        http.ServeFile(w, r, path)
    }

    if handlePath != "/" {
        handlePath += "/" + info.Name()
    }

    mainRouter.HandleFunc(handlePath, hf)
    return nil
})

(please optimize if the code is bad, I made the solution myself and I tried so many stuff to fit my needs)

Now with that I recevied the correct files with correct headers.

And I couldn’t find any solutions to work with custom headers using http.FileServer in http package. And please provide a easy solution if it exists.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement