apokryfos
apokryfos

Reputation: 40663

Getting Error: Cannot find module "." at webpackMissingModule

I'm trying to webpack an express application but I'm having the following problem wherever I try to retrieve the / page:

Getting Error: Cannot find module "." at webpackMissingModule

Here's code that reproduces this:

import express from 'express';

const app = express();
const port = 8088;

app.set('view engine', 'pug')

app.listen(port, () => console.log(`Listening on ${port}`));

app.get('/', (req, res) => {
    res.render('index');
});

Initially I thought it was because pug was not included in the modules so I tried adding require('pug') in the page but that just moved the error to the server launch rather than runtime.

Here's my webpack configuration:

const path = require('path');
module.exports = {
    entry: {
        index: path.join(__dirname, 'index.js')
    },
    target: 'node',
    module: {
        rules: [
            {
                test: /\.js$/,
                loader: 'babel-loader',
                include: [
                    __dirname
                ],
                exclude: /node_modules/
            }
        ]
    },
    resolve: {
        modules: [__dirname, 'node_modules']
    },
    output: {
        path: __dirname,
        filename: '[name].entry.js'
    }
}

I am using express 4.16, pug 2.0-rc4, webpack 3.8 and babel loader 7.1

I've also tried to include all node modules but then I get a different error (dP.f is not a function)

Upvotes: 4

Views: 9404

Answers (1)

Fabio Antunes
Fabio Antunes

Reputation: 22862

That's because although you are excluding node_modules from being compiled by babel, they are still being included on your bundle.

You also need to ignore node_modules from being included into your bundle.

Install webpack-node-externals

npm install webpack-node-externals --save-dev

And add two lines to your webpack config.

const path = require('path');
const nodeExternals = require('webpack-node-externals'); //include this

module.exports = {
    entry: {
        index: path.join(__dirname, 'index.js')
    },
    target: 'node',
    module: {
        rules: [
            {
                test: /\.js$/,
                loader: 'babel-loader',
                include: [
                    __dirname
                ],
                exclude: /node_modules/
            }
        ]
    },
    resolve: {
        modules: [__dirname, 'node_modules']
    },
    externals: [nodeExternals()], // just add this
    output: {
        path: __dirname,
        filename: '[name].entry.js'
    }
}

Upvotes: 4

Related Questions