Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bundle.js not found [Webpack]

[UPDATE] bundle.js was actually created in memory. The best way is to keep index.html and bundle.js (configured in webpack.config.js) in the same directory to avoid any issue.

I have been trying to render a simple html file with webpack but can't figure out why I'm getting a 404. I understand that bundle.js could not be found so I tried different paths but it didn't work, any ideas?

I would appreciate your help. Thanks.

app.js

var express = require('express')
var path = require('path')

const app = express();

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'html')

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

app.listen(3000, () => console.log('Example app listening on port 3000!'))

webpack.config.js

module.exports = {
  entry: ['./src/index.js'],
  output: {
    path: __dirname,
    publicPath: '/',
    filename: 'bundle.js'
  },
[...]

index.html

<!DOCTYPE html>
<html>
  [...]
  <body>
      <div class="container"></div>
  </body>
  <script src="./bundle.js"></script>
</html>

Folder structure

enter image description here

like image 340
Minh Pham Avatar asked Oct 29 '22 10:10

Minh Pham


1 Answers

You don't have specified a correct path to your index file. If you have it on a src directory the code will look like this:

entry: [
    path.resolve(__dirname, 'src/index')
  ],
[...]

Otherwise if you have it on your views directory, them the code will be the following:

 entry: [
        path.resolve(__dirname, 'views/index')
      ],
    [...]

And in your html file is <script src="/bundle.js"></script>


UPDATE

Base on your code at github try changing the following lines

entry: [
    path.resolve(__dirname, 'src/index')
  ],
  devServer: {
    contentBase: path.resolve(__dirname, 'src')
  },
    output: {
    path: __dirname + '/dist', // Note: Physical files are only output by the production build task `npm run build`.
    publicPath: '/',
    filename: 'bundle.js'
  },

The problem consist in that you're missing the path.resolve(...) in both your entry point and your devServer specifically

Hope helps :)

like image 139
manAbl Avatar answered Nov 12 '22 21:11

manAbl