Webpack on browser complains about require not defined

Viewed 743

Here is my folder structure:

src/
└───public/
    ├───index.js
    ├───controllers/
    ├───css/
    ├───js/
    ├───models/
    ├───vendor/
    └───views/
        └───partials/

I know it's not the best folder structure, but it's one of my earlier projects, and I wanted to test webpack on it.

Anyways the controllers, js, vendor all contain javascript code.

My webpack.dev.config is on the same level as src:

const path = require("path");
const common = require("./webpack.common");
const {merge} = require("webpack-merge");   

module.exports = merge(common, {
    target: 'node',
    mode: "development",
    output: {
        filename: "[name].bundle.js",
        path: path.resolve(__dirname, "dist")
    },
    plugins: [

    ],
    module: {

    }
});

As you can see it merges from webpack.common.js:

const nodeExternals = require('webpack-node-externals');
    
module.exports = {
    externals: [nodeExternals()],
    entry: {
        main: './src/index.js'
    },
    module: {
        rules: [
            {
                test: /\.js$/,

            }
        ]
    }
}

For now I am hardcoding the location of the bundled js file in my HTML docs, but on the browser when I run this, I see the message Uncaught ReferenceError: require is not defined and I am not sure how to fix it.

Here is index.js:

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

const Datastore = require('nedb');
const db = new Datastore({
    filename: path.join(__dirname, 'public/db/pfam.db'),
    autoload: true
});
module.exports.db = db;

app.use(express.static(__dirname + "/public"));
app.set('views', path.join(__dirname, 'public/views'));
app.set('img', path.join(__dirname, 'public/img'));
app.set('js', path.join(__dirname, 'public/js'));
app.set('css', path.join(__dirname, 'public/css'));
app.set('controllers', path.join(__dirname, '/public/controllers'));
app.set('db', path.join(__dirname, '/public/db'));

app.engine('handlebars', exphbs({
    defaultLayout: 'home',
    layoutsDir: path.join(__dirname, '/public/views')
}))

app.set('view engine', 'handlebars');
app.use(require('./public/controllers'))

console.log(`listening on port ... ${port}`)
app.listen(port);
1 Answers

The reason you are getting Uncaught ReferenceError: require is not defined is because your bundles contains require keyword, which is undefined in the browser?

Why do they contain require? Because you use nodeExternals from webpack-node-externals

From their docs:

All node modules will no longer be bundled but will be left as require('module').

Related