Node.js local server css file doesn't inject

514 views Asked by At

My dir looks like that :

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

I inject the css file with:

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());
})

I set up a local server with Node.js, when I do the request , the HTML file loads up, but the .css file doesn't connect for some reason.

I use this task for setting the server :

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

There are 3 answers

0
Arkadiy Stepanov On

To everyone that may encounter my problem,that would be the solution.

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

You can use express frame work to achieve this

Var express=require (express); var app=express(); // Now here you can attach static files app.use("../example.css",static("/..example"));

Hope it will work.

1
Joe Karlsson On

In order to serve up static files such as CSS, JS, or assets you will need to add them to your index.html, and your server will be responsible for serving up your assets. Gulp is a task runner, not a server, so you will need to set up a simple HTTP server to serve up your assets. You can certainty build an HTTP server with vanilla Nodejs, but the easiest way to do this is with Express. Your Express server might look something like this:

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');
});

Then in your index.html be sure to link your CSS files with the link tag.

<!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>