Search code examples
htmlcssnpmpackage.jsonnpm-live-server

Live-server not loading CSS


I have a CSS file linked with my HTML file.
The CSS doesn't load when loading the HTML file through live-server.

The CSS works fine when opening the HTML file directly through the browser.
I have my CSS file outside the directory where the HTML file is. When having live-server in my npm script, starting it with npm start, without any argument, it just shows all files of my workspace and the CSS works if I click on the directory where the main index.html is.
But if I add the path as an argument in the npm script, it only loads the HTML file without any CSS.

The link in the HTML file, index.html :

<link rel='stylesheet' type='text/css' href='../styles.css'>

In package.json :

"start": "live-server home"

The above doesn't load the CSS. Only

"start": "live-server"

works, which shows the working directory in the browser.
– I click the home directory and then the HTML file loads with the CSS.

When typing npm start from the terminal, my HTML file loads fine in my browser, but for some reason, the linked CSS file isn't loaded.
The CSS link should be fine, since it works correctly when opening directly from the browser.
Does the CSS file need to be in the same directory?


Solution

  • The reason this happens we can see from the live-server docs:

    The server is a simple node app that serves the working directory and its subdirectories.

    If a file is stipulated instead of a directory, or the directory does not contain the assets to be loaded by live-server, it will result in a 404. However, in the default settings for live-server, in the event of a 404, it will default to trying to read index.html which causes a MIME type error that it is trying to load "text/html" for many people facing this confusion.

    In general, when using live-server, try to create a public or dist directory that you plan to hold all your static content. Here is an example directory structure that is compiling typescript to a dist/js directory and sass to a dist/css directory:

    .
    ├── dist
    │   ├── css
    │   │   └── index.css
    │   ├── index.html
    │   └── js
    │       └── index.js
    ├── package.json
    ├── src
    │   ├── app.ts
    │   ├── index.ts
    │   └── sass
    │       └── main.scss
    └── yarn.lock
    
    

    You can then run "live-server dist" -- the key factor being I'm not asking live-server to look outside of the directory it is serving.

    Here is the live-server documentation for more information about configuration options