I am trying to load a bundle.js script in an ejs file?

问题: I am trying to run a react app from my index.ejs file. The bundle builds. However, when I route to this file, I receive a 404 on the bundle.js script, The index.ejs file is...

问题:

I am trying to run a react app from my index.ejs file. The bundle builds. However, when I route to this file, I receive a 404 on the bundle.js script, The index.ejs file is there and can render content, just not the react app. Can anyone see what I am missing? Here is what my index.ejs file looks like:

<!DOCTYPE html>
<html>
  <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">
    <title>Bookie Lou</title>
  </head>
  <body>
    <div id="root"></div>
      <script src="bundle.js"></script>
  </body>
</html>

Here is what my routes file looks like where I establish that I want index.ejs to render when a get request is made to '/index/home' :

const express = require('express');
const router = express.Router();
const { ensureAuthenticated } = require('../config/auth');

router.get('/', (req, res) => res.render('welcome'))

router.get('/dashboard', ensureAuthenticated, (req, res) =>
  res.render('dashboard', {
    user: req.user
  })
);
router.get('/index/home', (req, res) => res.render('index'));

module.exports = router;

My webpack looks like this:

module.exports = {
  context: 
  path.join(__dirname, './src/'),

  entry: './index.jsx',
  devtool: 'source-map',
  output: {
    filename: 'bundle.js',
    path: path.join(__dirname, '/build'),
  },

  resolve: {
    extensions: ['.js', '.jsx','.json', '.css']
  },

  module: {
    rules: [
      {
        test: /.jsx?$/,
        exclude: /node_modules/,
        loaders: ['babel-loader'],
      },
      {
        test: /.index$/,
        use: 'file?name=[name].[ext]'
      },
      {
        test: /.html$/,
        loader: 'file?name=[name].[ext]',
      },
      {
        test: /.(gif|jpe?g|png|ico)$/,
        use: 'url-loader?limit=1000'
      },
      {
        test: /.(css|less)$/,
        use: ['style-loader', 'css-loader', 'less-loader']
      }
    ],
  }
};

My react files, app.jsx and index.jsx, are located in my src folder. My bundle.js file is located in a folder named build. Both folders are at root.


回答1:

I recommended you use html-webpack-plugin to inject bundle.js to html.

https://github.com/jantimon/html-webpack-plugin

  • 发表于 2019-03-19 06:26
  • 阅读 ( 194 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除