While HTML and CSS collaborate seamlessly during development, CSS mysteriously disappears when transitioning to production mode

I am brand new to this field and I apologize in advance for any mistakes. Currently, I am working on a node.js project using webpack and HTML loader. To test the project, I am utilizing the dev server dependency to run it locally. All models, views, and template index.html files are located in the 'src' folder, while the webpack config, package.json, and server.js files can be found in the root directory. The webpack HTML loader is responsible for loading the index.html file into the 'dist' folder, which contains a 'css' folder with style.css inside. Everything functions smoothly in development mode, and I can successfully run the page on my localhost. However, issues arise when I attempt to run "npm run start" (which involves "node server.js"). Subsequently, when I try to access the page on localhost, the styling seems to break, even though the interactive functionalities of the page work as intended. I suspect that the 'href' linking the CSS in the index.html file may be incorrect. Does anyone have insights on what could be wrong in my code? Below, I have shared all the images and code snippets that I am currently utilizing.

https://i.sstatic.net/EzzJx.png

https://i.sstatic.net/zCyL2.png

webpack.config.js

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
    entry: ['./src/js/index.js'],
    output: {
        path: path.resolve(__dirname, 'dist'),
        filename: 'js/bundle.js'
    },
    devServer:{
        contentBase: './dist'
    },
    plugins: [
        new HtmlWebpackPlugin({
            filename: 'index.html',
            template: './src/index.html'
        })
    ],
    module: {
        rules: [
            {
                test: /\.js$/,
                exclude: /node_modules/,
                use:{
                    loader: 'babel-loader'
                }
            }
        ]
    }
}

package.json file

{
  "name": "forkify",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "dev": "webpack --mode development",
    "dev-start": "webpack-dev-server --mode development --open",
    "heroku-postbuild": "webpack --mode production",
    "start": "node server.js"
  },
  "author": "Sayeedur Rahman",
  "license": "ISC",
  "devDependencies": {
    "@babel/core": "^7.9.0",
    "@babel/preset-env": "^7.9.5",
    "babel-loader": "^8.1.0",
    "html-webpack-plugin": "^4.2.0",
    "webpack": "^4.20.2",
    "webpack-cli": "^3.1.1",
    "webpack-dev-server": "^3.10.3"
  },
  "dependencies": {
    "axios": "^0.19.2",
    "core-js": "^3.6.5",
    "express": "^4.17.1",
    "fractional": "^1.0.0",
    "regenerator-runtime": "^0.13.5",
    "uniqid": "^5.2.0"
  },
  "engines": {
    "node": "12.16.1",
    "npm": "6.13.4"
  }
}

server.js file

const express = require('express');
const path = require('path');
const port = process.env.PORT || 8080;
const app = express();

app.use(express.static(__dirname + '/dist'));

app.get('/', (req, res) =>{
    res.sendFile(path.resolve(__dirname, '/dist', 'index.html'))
});

app.listen(port);
console.log(`server started on ${port}`);

index.html file section

<!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 href="https://fonts.googleapis.com/css?family=Nunito+Sans:400,600,700" rel="stylesheet">
    <link rel="stylesheet" href="css/style.css">
    <link rel="shortcut icon" href="img/favicon.png" type="image/x-icon">
    <title>forkify // Search over 1,000,000 recipes</title>
</head>

Answer №1

I recommend trying this solution to see if it resolves the issue. Add the following line of code after your routes in the server.js file:

app.use(express.static(path.resolve(__dirname, './dist')));

Make sure to include a dot before /dist.

If that doesn't solve the problem, you could also consider modifying the following line in your index.html:

<link rel="stylesheet" href="../../css/style.css">

or

<link rel="stylesheet" href="../css/style.css">

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

"Reposition all elements contained within a div that have a specific class

I'm completely new to Javascript and I've been trying to move all elements with a specific class inside a particular div. After doing some research, I found a solution that worked using IDs. However, when I tried to adapt it to work with classNam ...

The res.send() method in Restify was not triggered within the callback function of an event

Currently, I am utilizing restify 2.8.4, nodejs 0.10.36, and IBM MQ Light messaging for a RPC pattern. In this setup, when the receiver has the result ready, it emits an event. The below restify POST route is supposed to capture this event along with the ...

"Encountering a halt in my Node.js Application as it waits endlessly

I'm currently following a tutorial on creating a collaborative canvas drawing application using Node.js and Socket.io. I've included the source file below which is used to create the server. However, when I try to open it in my browser, it gets s ...

Attempting to achieve a carousel animation using jQuery

Upon loading the page, only one character out of four is displayed. Two arrows are provided - one on the left and one on the right. Clicking on the left arrow causes the current character to fade out and the previous character to fade in. Clicking on the r ...

Getting an error message saying Express cannot locate the jade views

Currently delving into Express (+ Node.js) and facing a puzzling issue: Error: Failed to search for view "index" in the views directory "../NODE_tests/Tutorial/app/views" I do have an index.jade in the directory "../NODE_tests/Tutorial/app/views" doctyp ...

Does App.all triggered by static file access?

I have the following code in my server.js: app.all("*", function(req, res, next) { // This code block is only executed when a post or get request is made next(); }); However, I am interested in receiving an event notification whenever a static file ...

Could not locate the provider: $stateProvider

It's puzzling to me why this code is not recognizing the $stateProvider. Uncaught Error: [$injector:modulerr] Failed to instantiate module app due to: Error: [$injector:unpr] Unknown provider: $stateProvider This is a simple example of a module: ( ...

Is it possible to register multiple handlers for a single event in socket.io?

When it comes to explaining how to handle receiving events, the documentation for socket.io doesn't specify if multiple event handlers can be used for the same event. For instance, if I have two components that both need to handle the event io.on(&apo ...

Navigating Dynamically between tabs - A How-to Guide

I am working on a mat-tab Angular app where I need to dynamically generate links and transfer them to a navLinks object. Despite ensuring that the concatenation is correct, it seems like my approach is not working as expected. Here's a glimpse of what ...

swap out the CSS class for my own class dynamically

When I display HTML code like this <div class="btn btn-pagination"> <i class="fa fa-angle-right"></i> </div> and want to replace fa fa-angle-right with myClass when the page loads. I attempted: $(document).ready(function () { ...

Flexbox: changing the order and arranging columns in a vertical stack

At a specific screen size, I need to rearrange three columns on my website. Currently, the layout consists of two columns that are 1/4 width each with a 1/2 width column in between them. I want to change the two 1/4 width columns into 1/2 widths and stac ...

CSS transformation: skewing without any blurring effects

Is there a way to create tilted drivers with borders and text without sacrificing the sharpness of the font and border? I have used the transform: skew(); CSS rule for tilting, but it has caused blurriness. How can I add font smoothing and maintain sharp b ...

Concurrent requests hitting multiple ExpressJS routes simultaneously

While configuring my routes for an expressjs app, I encountered the issue of two routes being executed when accessing a single endpoint. This is an excerpt from my code: app.get("/forgot-password", (req, res) => { .... }); app.get("/:modelName/:id ...

Retrieve variables from an external JavaScript file

I need to fetch the currentID variable from renderermain.js and utilize it in renderermem.js. However, I am looking for a way to achieve this without modifying mem.html: <script src="renderermain.js"></script> <script src="renderermem.js"& ...

Before creating a new user in passportjs, ensure that there are 2 fields present in the mongoose schema

Currently, in my express app using passportjs, I have implemented a section of code that checks mongoDB to verify if 'email' or 'businessName' are already registered. The part of the code provided below showcases how this functionality ...

Increment and decrement the like count on fa-heart multiple times

Is there a way to increment the count of a fa-heart value on click and decrement it on the second click? The issue I'm facing is that I have multiple fa-heart elements on the same page, making it challenging to increment or decrement the clicked fa-h ...

What could be the reason for the content not being displayed in this react component?

I am currently working on a project that involves displaying content obtained from backend routes via axios to the Showcase component. However, I am experiencing issues with rendering the contents as expected despite the updated state console.log(cont) sho ...

I am encountering an issue with the callback function not functioning properly when utilizing react-flutterwave-rave in test mode. What could

I have integrated Flutterwave as the payment system for my web application that I am currently developing using React. To facilitate this integration, I have utilized the react-flutterwave-rave package available on npm. The implementation is functioning ...

Is there a way to create a customized calendar in Node.js?

I am looking for a way to showcase a calendar in a localized format, not only in terms of language but also supporting non-Gregorian calendars such as Persian, Chinese, or Buddhist. In the past, when I worked with Java, I relied on ICU4J for this task. Ho ...

When utilizing customize-cra to modify antd less variables, it results in the generation of numerous redundant CSS files during the build

While utilizing customize-cra to override antd less variable, I have encountered an issue where it generates multiple duplicate CSS files during the build process. According to the documentation provided by antd, if I opt for the default import of CSS by ...