skip to Main Content

I’ve created a simple TS project with the following file structure:

dairyproducts.github.io/
├── package.json
├── public/
│   ├── images/
│   ├── index.html
├── src/
│   └── index.ts
├── dist/
│   └── index.js
└── tsconfig.json

Where index.js is the compiled index.ts. The .ts file contains a single hello world console log.
In index.html I have the following line in my header tag:
<script src="../dist/index.js"></script>

Starting the server with http-server and opening the index.html file throws a 404 error for GET /dist/index.js.

However, moving index.js to the public folder and changing the script tag source to "index.js" makes it run perfectly fine. Moving index.js to the root folder and making the source ../index.js doesn’t work though.

To my understanding, ../ is supposed to refer to the directory above the current directory, so I don’t know why this wouldn’t work.

Update: http-server ./ -p 8080 --cors serves a file directory of the root folder, and when the public folder is navigated to the HTML file loads the index.js as expected. I guess the problem now is just finding a way to make the "entry point" of the server public/index.html while still serving from root.

2

Answers


  1. This is very likely because your local http-server uses public folder as its root. When index.html is opened in the browser it appears at the root level, and any relative URL starting with ../ makes no sense.

    Practically, everything outside public folder is unavaliable from within browser in this scenario.


    Edit

    There are some pieces to puzzle why the command
    http-server -p 8080 --cors .
    did not work.

    1. http-server sets the root path to ./public when the path
      is not specified AND public folder exists (see details here).
    2. --cors is not just a flag but may be followed by list of
      headers. So the last . from the command is recognized as a custom
      header, effectively leaving the root unspecified.

    As a result, the server is started with public folder as its root.

    How to fix this?

    Start the server with command
    http-server ./ -p 8080 --cors
    and access the document from
    http://localhost:8080/public/index.html.

    Login or Signup to reply.
  2. You can only import your assets like CSS or JavaScript files directly when that files are on the location of public.
    Please press F12 key, and just see the source field, can you find the dist folder, maybe you can not.
    That’s why you can’t access that file.
    So, please check it is located in your public folder.

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