Webpack – 获取节点模块进入Bundle并加载到html文件

我正试图通过WebPack在浏览器中使用node_modules。 我读过教程和开始的步骤,但卡住了。

我已经使用webpack生成下面的webpackconfigurationbundle.js和去浏览我的index.html在Chrome浏览器中我得到的错误:

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

我需要做什么额外的步骤才能让浏览器识别要求?

的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'] } } ] } }; 

在你的webpack.config.js你指定了你想为Node.js构build这个包:

 target: 'node', 

和webpack决定保持require调用,因为Node.js支持他们。 如果你想在浏览器中运行它,你应该使用target: 'web'来代替。