简体   繁体   中英

webpack: express can't find bundle Error 404

I know this question is was asked a lot but i have tried everything and nothing work! Here the thing: I am working on an Isomorphic React App for practise witch a big copy of this tutorial of 2017 that i try to update it https://medium.com/@phoebe.greig/headache-free-isomorphic-app-tutorial-react-js-react-router-node-js-ssr-with-state-and-es6-797a8d8e493a

app folder

build folder

A big part of her code is now deprecated and i recode it. One important things, I use webpack for compile all of the folder of the app including the index.js file and not babel for all the folder and only webpack for the index.js file like she did.

The problem is I render my HTML page by a js fonction renderFullPage.js

export default function renderFullPage(html, preloadedState) 
    return `
    <!DOCTYPE html>

    <html lang="fr">
        
        <head>
            <meta charset="UTF-8"/>
            <title> Isomorphic Router React Mongoose App initialised with data</title>
        </head>
    
        <body>
            
            <div id="root">
                ${html}
            </div>
            <script>
                window.__PRELOADED_STATE__ = ${JSON.stringify(preloadedState).replace(/</g, '\\u003c')}
            </script>
            <script type="application/javascript" src="bundle-app.js"></script>
            
        </body>
    </html>
    
    `;
}

My goal is to call a request to the express server who will collect with Mongoose MongoDB's data and send it back to the client. Before continuing with React, I want to check if everything is ok by using console.log for some data in client.the HTML using React load perfectly That the problem: no console.log is display in client because it can't load the bundle-app.js file from the build folder. I get everytime an Error 404 and i believe that it's because i set my path wrong but i have no idea what i doing wrong. Error loading Script http://localhost:8080/bundle-app.js I have no idea in what path my server got loached also.

Here are the app.js file from app/server:

import path from 'path';
import express from 'express';
import cors from 'cors';

import router from './router';

const app = express();

const assets = express.static(path.join(__dirname,'../'));

app.use(cors());
app.use(assets);

app.get("*", router);

export default app;

And here and the webpack.config.js:

{
  "name": "ssr-react-router-mongoose-isomorphic-app",
  "version": "1.0.0",
  "description": "isomorpic app",
  "main": "./app/index.js",
  "scripts": {
    "build:server": "babel ./app/server -d build/server",
    "build:watch:server": "babel ./app/server -d build/server --watch",
    "build:client": "webpack --mode development --config webpack.config.js/  --progress ",
    "build:watch:client": "webpack-dev-server -d --hot --config webpack.config.js --watch",
    "build:prod": "npm run build:server && npm run build:client",
    "start": "npm run build:prod && NODE_ENV=production node ./build/server/index.js",
    "start:dev": "parallelshell \"npm run build:watch:client\" \"nodemon ./build/server/bundle-server.js\" ",
    "start:dev:client": "webpack-dev-server"
  },
  "author": "Rando Mathias",
  "license": "ISC",
  "dependencies": {
    "babel-polyfill": "^6.26.0",
    "cors": "^2.8.5",
    "express": "^4.17.1",
    "mongoose": "^5.10.6",
    "react": "^16.13.1",
    "react-dom": "^16.13.1",
    "react-router-dom": "^5.2.0"
  },
  "devDependencies": {
    "@babel/cli": "^7.11.6",
    "@babel/core": "^7.11.6",
    "@babel/preset-env": "^7.11.5",
    "@babel/preset-react": "^7.10.4",
    "babel-loader": "^8.1.0",
    "file-loader": "^6.1.0",
    "html-webpack-plugin": "^4.5.0",
    "nodemon": "^2.0.4",
    "parallelshell": "^3.0.1",
    "webpack": "^4.44.2",
    "webpack-cli": "^3.3.12",
    "webpack-dev-server": "^3.11.0"
  }
}


const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
var fs = require('fs');

var nodeModules = {};
fs.readdirSync('node_modules')
  .filter(function(x) {
    return ['.bin'].indexOf(x) === -1;
  })
  .forEach(function(mod) {
    nodeModules[mod] = 'commonjs ' + mod;
  });

var config = { // la configuration commune pour les 2 modes.
  devtool: 'inline-source-map',
  context: path.resolve(__dirname, './app'),
  entry: {
    '/bundle-app': ['babel-polyfill','./index.js'],
    '/components/bundle-components': ['./components/App.js','./components/Home.js'],
    '/server/bundle-server': ['./server/app.js','./server/index.js','./server/renderFullPage.js','./server/router.js','./server/routes.js'],
    '/services/bundle-services': './services/getMongoose_data.js'
  },
  target:'node',
  output: 
  {
    path: path.resolve(__dirname, './build'), // on crée l'application de sortie dans un dossier "public"
    publicPath: '/',
    filename: '[name].js', // les fichier bundle seront dans le chemin qui est le nom des fichiers d'entrées
  },
  module: 
  {
    rules: [
      {
        test: /\.(js|jsx)$/, // pour les fichiers de type js et jsx
        loader: 'babel-loader', // on charge babel un transcompileur 
        exclude: /node_modules/,
        options: 
        {
          presets: ['@babel/preset-env', '@babel/preset-react']
        }
      },
    ]
  },
  // plugins: [
  //   new HtmlWebpackPlugin({
  //       template: './app/server/renderFullPage.js',
  //       filename: 'index.html',
  //       inject: 'body',
  //   }),
  // ],
};

module.exports = (env, argv) =>
{
    return config;
}

I want to load the bundle-app.js from the build folder Thanks in advance for your help

You start your script from root of your project.

"start": "npm run build:prod && NODE_ENV=production node ./build/server/index.js",

And tries to access static files by setting pass to them as below.

const assets = express.static(path.join(__dirname,'../'));

But issue here is that path should be relative to the script start folder.
In your case it is your project root folder where you execute npm start command.

You need to change static files path to set be relative to your project root instead of server bundle.

If I'm right it will be as below.

const assets = express.static(path.join('./build'));

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