Node.js本地服务器css文件不注入

fdx2calv  于 2023-05-28  发布在  Node.js
关注(0)|答案(3)|浏览(167)

我的dir看起来是这样的:

|-project
   -gulpfile.js  
   |-build
     -index.html
     |-js
       -app.min.js
       -vendors.min.js
     |-styles
       -all.css
       -vendors.min.css

我插入css文件:

gulp.task('index',function () {
return gulp.src('src/index.html')
    .pipe(inject(gulp.src(['http://localhost:5000/styles/all.css'], {read: false})))
    .pipe(gulp.dest('build'))
    .pipe(livereload());
})

我用Node.js设置了一个本地服务器,当我发出请求时,HTML文件加载了,但是.css文件由于某种原因没有连接。
我使用此任务设置服务器:

gulp.task('connect', function() {
 connect.server({
   root: 'build',
   livereload: true,
    port: 5000
 });
});
xuo3flqw

xuo3flqw1#

您可以使用快速框架来实现这一点
Var express=require (express); var app=express(); // Now here you can attach static files app.use("../example.css",static("/..example"));
希望它能起作用。

pod7payv

pod7payv2#

为了提供静态文件,如CSS,JS或资产,您需要将它们添加到index.html,您的服务器将负责提供您的资产。Gulp是一个任务运行器,而不是服务器,因此您需要设置一个简单的HTTP服务器来为您的资产提供服务。你可以用普通的Nodejs构建一个HTTP服务器,但是最简单的方法是使用Express。您的Express服务器可能看起来像这样:

const express = require('express');
const app = express();

// serve static files in public/build directory
app.use(express.static('./build'));

// start the server on port 3000
const server = app.listen(3000, function() {
  console.log('Server started on http://localhost:3000');
});

然后在你的index.html中确保用link标签链接你的CSS文件。

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Simple HTTP Server</title>
  <link rel="stylesheet" href="/css/styles.css">
</head>
<body>
  <h1>Simple HTTP Server</h1>
</body>
</html>
8i9zcol2

8i9zcol23#

对于每个可能遇到我的问题的人,这将是解决方案。

.pipe(inject(gulp.src(['build/styles/all.css'], {read: false}), {ignorePath: 'build'} ))

相关问题