【发布时间】:2020-05-25 20:09:39
【问题描述】:
问题
index.html 没有加载我的.css 文件。我设置了一个gulp.js 文件,我觉得文件夹目录可能是这里的障碍。我在/src/scss 文件夹中的.scss 文件在我的/build/css 文件夹中正确编译为css。
期望的结果
让 index.html 加载我的 css 文件并可以使用 Firefox 样式编辑器查看。
文件夹目录
基本 HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<link type="text/css" href="../build/css/styles.css" />
<title>Boiler plate</title>
</head>
<body>
<h1>Project name goes here</h1>
<script src="./scripts/index.js"></script>
</body>
</html>
Gulp.js 文件
// const gulp = require('gulp');
const { series, src, dest, watch } = require('gulp');
const sass = require('gulp-sass');
const browserSync = require('browser-sync').create();
//Compile SCSS into CSS
function style() {
// 1. Find SCSS file
return (
src('./src/scss/**/*.scss')
// 2. Pass through sass compiler
.pipe(sass())
.on('error', sass.logError)
// 3. Where do save compiled css
.pipe(dest('./build/css'))
// 4. Stream changes to all browsers
.pipe(browserSync.stream())
);
}
// Watch for changes in src directory and make updates
function watchFiles() {
browserSync.init({
server: {
baseDir: './src'
}
});
watch('./src/scss/**/*.scss', style);
watch('./src/*.html').on('change', browserSync.reload);
watch('./src/scripts/**/*.js').on('change', browserSync.reload);
}
exports.style = style;
exports.watchFiles = watchFiles;
exports.default = series(style, watchFiles);
当前错误
Firefox 控制台显示以下错误
The resource from “http://localhost:3000/build/css/styles.css” was blocked due to MIME type (“text/html”) mismatch (X-Content-Type-Options: nosniff)
当我删除 rel="stylehseet" 并替换为 type="text/css" 时,错误消失了。但是,同样的问题仍然存在……没有加载 CSS 文件。
【问题讨论】:
-
首先,使用相对路径(“../build/css/styles.css”)不是一个好主意,因为这是相对于当前页面路径的。因此,即使它适用于 index.html,它也不适用于 /blog/entries.html 或类似的东西(如果您有更多页面)。其次,您的 css 文件是如何由哪个服务器提供的?如果您的服务器添加缓存标头告诉浏览器缓存文件,您的浏览器将不会加载更改的 css,因为文件名没有更改。检查您的浏览器开发工具,网络选项卡,以获取 css 文件的响应标头。
-
这很奇怪,你检查文件是否被加载?您是否在浏览器控制台上收到错误消息?文件是否出现在网络选项卡中?
-
如果您将此部分
href="../build/css/styles.css"更改为href="./build/css/styles.css"会发生什么? -
@dirkgroten 我检查了网络。 css 的状态是 404。只是找不到
-
@GabrielRodriguesSegalla 我已更新控制台中的错误。我在网络选项卡中得到 404。
标签: html css node.js sass gulp