Webpack - 将节点模块放入 Bundle 并加载到 html 文件中
Webpack - Getting node modules Into Bundle and loading into html file
我正在尝试通过 WebPack 在浏览器中使用 node_modules。我已阅读教程和开始步骤,但卡住了。
我使用 webpack 通过下面的 webpack 配置生成 bundle.js,然后在 Chrome 浏览器中转到我的 index.html 时出现错误:
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 构建此捆绑包:
target: 'node',
并且 webpack 决定保留 require
调用,因为 Node.js 支持它们。如果你想在浏览器中 运行 它,你应该使用 target: 'web'
代替。
我正在尝试通过 WebPack 在浏览器中使用 node_modules。我已阅读教程和开始步骤,但卡住了。
我使用 webpack 通过下面的 webpack 配置生成 bundle.js,然后在 Chrome 浏览器中转到我的 index.html 时出现错误:
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 构建此捆绑包:
target: 'node',
并且 webpack 决定保留 require
调用,因为 Node.js 支持它们。如果你想在浏览器中 运行 它,你应该使用 target: 'web'
代替。