实时服务器未加载 css 文件

Voi*_*ips 5 html css npm package.json npm-live-server

我有一个与我的 html 文件链接的 css 文件。通过实时服务器加载 html 文件时,我的 css 不起作用。

直接通过浏览器打开 html 文件时,css 工作正常。我的 css 文件位于 html 文件所在的目录之外。当我的 npm 脚本使用 live-server 作为 npm start 时,没有任何参数,它只显示我的工作区的所有文件,如果我点击我的 html 文件所在的目录,css 将起作用。但是如果我添加 html 文件作为 live-server 的参数,它只会加载 html 文件而没有任何 css 更改。

html:

<link rel='stylesheet' type='text/css' href='../styles.css'>
Run Code Online (Sandbox Code Playgroud)

包.json:

"start": "live-server home/index.html"
Run Code Online (Sandbox Code Playgroud)

或者

"start": "live-server home"
Run Code Online (Sandbox Code Playgroud)

或者

"start": "live-server home/index.html && styles.css"
Run Code Online (Sandbox Code Playgroud)

都有相同的结果。仅有的

"start": "live-server"
Run Code Online (Sandbox Code Playgroud)

works,它显示浏览器上的工作目录。我单击主目录,然后使用 css 加载 html 文件。

从终端输入 npm start 时,我的 html 文件可以在浏览器上正常加载,但由于某种原因链接的 css 文件没有加载。css 链接代码应该没问题,因为它在直接从浏览器打开时可以正常工作。css文件需要在同一个目录下吗?

And*_*ist 2

发生这种情况的原因我们可以从实时服务器文档中看到:

\n
\n

服务器是一个简单的节点应用程序,为工作目录和子目录提供服务。

\n
\n

如果规定的是文件而不是目录,或者目录中不包含live-server要加载的资源,就会导致404。但是在live-server的默认设置下,一旦出现404 ,它会默认尝试读取index.html,这会导致 MIME 类型错误,即它试图为许多面临这种困惑的人加载“text/html”。

\n

一般来说,在使用 live-server 时,尝试创建一个 public 或 dist 目录来保存所有静态内容。下面是一个示例目录结构,它将 typescript 编译到 dist/js 目录,将 sass 编译到 dist/css 目录:

\n
.\n\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 dist\n\xe2\x94\x82\xc2\xa0\xc2\xa0 \xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 css\n\xe2\x94\x82\xc2\xa0\xc2\xa0 \xe2\x94\x82\xc2\xa0\xc2\xa0 \xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 index.css\n\xe2\x94\x82\xc2\xa0\xc2\xa0 \xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 index.html\n\xe2\x94\x82\xc2\xa0\xc2\xa0 \xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 js\n\xe2\x94\x82\xc2\xa0\xc2\xa0     \xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 index.js\n\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 package.json\n\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 src\n\xe2\x94\x82\xc2\xa0\xc2\xa0 \xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 app.ts\n\xe2\x94\x82\xc2\xa0\xc2\xa0 \xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 index.ts\n\xe2\x94\x82\xc2\xa0\xc2\xa0 \xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 sass\n\xe2\x94\x82\xc2\xa0\xc2\xa0  \xc2\xa0\xc2\xa0 \xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 main.scss\n\xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 yarn.lock\n\n
Run Code Online (Sandbox Code Playgroud)\n

然后,您可以运行“live-server dist”——关键因素是我没有要求 live-server 查看它所服务的目录之外的内容。

\n

这是实时服务器文档,了解有关配置选项的更多信息

\n