How can I have webpack skip a module if it doesn't exist

3.8k Views Asked by At

I'm trying to use WebPack to include "showdown". The problem is that showdown will require("fs") and check the return value. This makes WebPack throw an error.

It seems like it should be possible to configure Webpack to generate a shim so that call to require("fs") will return false.

Maybe one of these techniques might work: http://webpack.github.io/docs/shimming-modules.html

Here's the Showdown.js code. If I comment out this code inside the node modules directory, the problem is solved. However, there should be a better way.

//
// Automatic Extension Loading (node only):
//

if (typeof module !== 'undefind' && typeof exports !== 'undefined' && typeof require !== 'undefind') {
    var fs = require('fs');

    if (fs) {
        // Search extensions folder
        var extensions = fs.readdirSync((__dirname || '.')+'/extensions').filter(function(file){
            return ~file.indexOf('.js');
        }).map(function(file){
            return file.replace(/\.js$/, '');
        });
        // Load extensions into Showdown namespace
        Showdown.forEach(extensions, function(ext){
            var name = stdExtName(ext);
            Showdown.extensions[name] = require('./extensions/' + ext);
        });
    }
}
4

There are 4 best solutions below

0
On

The solution was to switch to marked: https://www.npmjs.org/package/marked. The showdown library is problematic as far as modules go.

1
On

This seems to be a Showdown problem rather than a webpack one. The code that requires fs is intended to only be run in a node environment. Unfortunately there are some typos in the code that checks if it's running in node (the first if statement in the code you posted, undefind instead of undefined).

There is an pull request that fixes this which hasn't been merged yet.

To be honest it looks like the Showdown library is no longer maintained (last commit November 2012) so you may be better off looking for an alternative if possible.

0
On

This issue should be fixed in showdown v >=1.0.0

0
On

Add it to noParse e.g.

var config = {
    output: {
        path: buildPath,
        filename: 'bundle.js'
    },
    module: {
        noParse: [
            /showdown/,
        ],

And webpack will assume it does not contain any useful calls to require