Search code examples
javascriptnode.jswebpackbundle

Webpack - Getting node modules Into Bundle and loading into html file


I am trying to use node_modules in the browser via WebPack. I've read the tutorial and beginning steps but am stuck.

I have used webpack to generate bundle.js with the webpack config below and upon going to my index.html in Chrome browser I get the error:

Uncaught ReferenceError: require is not defined at Object.<anonymous> (bundle.js:205)

What additional steps do I have to do to get the browser to recongnize require?

index.html

<script src="bundle.js"></script>

<button onclick="EntryPoint.check()">Check</button>

index.js

const SpellChecker = require('spellchecker');

module.exports = {
      check: function() {
            alert(SpellChecker.isMisspelled('keng'));
      }
};

package.json

{
  "name": "browser-spelling",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "dependencies": {
    "node-loader": "^0.6.0",
    "spellchecker": "^3.3.1",
    "webpack": "^2.2.1"
  }
}

webpack.config.js

module.exports = {
    entry: './index.js',
    target: 'node',
    output: {
        path: './',
        filename: 'bundle.js',
        libraryTarget: 'var',
        library: 'EntryPoint'
    },
    module: {
        loaders: [
            {
                test: /\.node$/,
                loader: 'node-loader'
            },
            {
                test: /\.js$/,
                exclude: /node_modules/,
                loader: 'babel-loader',
                query: {
                    presets: ['es2015']
                }
            }
        ]
    }
};

Solution

  • In your webpack.config.js you specified that you want to build this bundle for Node.js:

    target: 'node',
    

    And webpack decided to keep require calls, because Node.js supports them. If you want to run it in a browser, you should use target: 'web' instead.