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']
}
}
]
}
};
To configure Webpack to bundle HTML we'll use our first plugin, a dependency called HtmlWebpackPlugin. Remember, loaders offer functionality to files before Webpack bundles them, whereas plugins modify the entire bundle itself.
Webpack allows you to define externals - modules that should not be bundled. When bundling with Webpack for the backend - you usually don't want to bundle its node_modules dependencies. This library creates an externals function that ignores node_modules when bundling in Webpack.
Webpack is a static module bundler for JavaScript applications. It takes modules, whether that's a custom file that we created or something that was installed through NPM, and converts these modules to static assets.
Chunk: This webpack-specific term is used internally to manage the bundling process. Bundles are composed out of chunks, of which there are several types (e.g. entry and child).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With