简体   繁体   中英

How to refer a css file from index.html in React

I have a folder called assets which have a styles.css and then I have index.html which I would want to reference styles.css but for some reason it can't.

My current solution is this:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8" />
        <title>My App</title>
        <link rel="stylesheet" href="/styles.css">

    </head>
    <body>
        <div id="app"></div>
        <script type="text/javascript" src="/bundle.js"></script>
    </body>
</html>

And I have the node server running like this:

var webpack = require("webpack");
var config = require("./webpack.config.js");

var http = require('http');
var express = require('express');
var app = express();
var proxy = require('http-proxy-middleware');
var path = require('path');

const compiler = webpack(config);


app.use(require("webpack-dev-middleware")(compiler, {
  noInfo: true,
  publicPath: "/"
}));

app.use(require("webpack-hot-middleware")(compiler));

app.use('/auth', proxy('http://localhost:8081', {changeOrigin: true}));
app.use('/api', proxy('http://localhost:8081', {changeOrigin: true}));

app.get("*", function(req, res) {
  res.sendFile(__dirname + '/index.html');
});

/**
 * Anything in public can be accessed statically without
 * this express router getting involved
 */

app.use(express.static(path.join(__dirname, 'assets'), {
  dotfiles: 'ignore',
  index: false
}));

var server = http.createServer(app);
server.listen(3000, function() {
  console.log("express listening at localhost:3000");
});

This is not working for me it cannot find the css file, how can I make it so I can reference the css file from index.html. Also I have index.js on my src folder which is used as an entrance file for running the whole React App.

Add the route for styles.css before app.get("*",...)

app.get("/styles.css", function(req, res) {
  res.sendFile(__dirname + '/styles.css');
});

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