简体   繁体   中英

Loading static assets in Nodejs

What is the correct approach to loading static files. I'm trying to use Semantic UI. I have followed the basic steps here: http://semantic-ui.com/introduction/getting-started.html . I have Node installed, NPM installed, ran the gulp process and built the files. I have also required the files like this:

link(rel='stylesheet', type='text/css', href='/semantic/dist/semantic.min.css')
script(src='semantic/dist/semantic.min.js')

My project structure is this:

server.js

views/  
  index.jade

semantic/  
  dist/
    semantic.min.css
    semantic.min.js

I have checked in the browser and there is no console error but those files aren't listed as a resource. I have checked the server logs and there's no error.

The only thing I can think of, is that I need to set up a public directory to serve static files like:

app.use(express.static(path.join(__dirname, 'public')));

Edit I have attempted to do this:

app.use(express.static('public'));

And have moved the files into the public directory. It loads because I can navigate to them in the browser but they aren't being applied.

Is there anyway to require them from the semantic folder? I like them to be built and required from the same space.

Edit

View:

<!DOCTYPE html>  
<html lang="en">
  <head>
    <title>Title
      <script src="js/jquery.min.js"></script>
      <link rel="stylesheet" href="css/semantic.min.css">
      <script src="js/semantic.min.js"></script>
    </title>
    <body>
      <button class="ui button"> Follow</button>
    </body>
  </head>
</html>

Serverjs:

var express    = require('express'),
    ejs        = require('ejs'),
    path       = require('path'),
    app        = express();

app.use(express.static(path.join(__dirname, 'public')));
app.set('view engine', 'ejs');
app.set('views', './views');


app.get('/', function(req, res) {

  res.render('index');
});

var server = app.listen(8080, function() {
  var host = server.address().address;
  var port = server.address().port;
  console.log('Node is listening at http://' + host + ':' + port);
});

Add this line in your app.js file.

app.use(express.static(path.join(__dirname,'public')));

Then create a folder named public in the project root directory and move the css and js files to this folder. A better way of organising things would be to create folders named css and javascript inside the public directory and then place css and js files in these folders.

Then in your template file, include these by adding :

link(rel='stylesheet', type='text/css', href='css/semantic.min.css')
script(src='javascript/semantic.min.js')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM