Cli*_*ick 6 javascript bundle node.js webpack
我正在尝试通过 WebPack 在浏览器中使用 node_modules。我已经阅读了教程和开始步骤,但被卡住了。
我已经使用 webpack 使用下面的 webpack 配置生成 bundle.js,在 Chrome 浏览器中访问我的 index.html 时出现错误:
Uncaught ReferenceError: require is not defined
at Object.<anonymous> (bundle.js:205)
我必须执行哪些额外步骤才能让浏览器识别需要?
索引.html
<script src="bundle.js"></script>
<button onclick="EntryPoint.check()">Check</button>
Run Code Online (Sandbox Code Playgroud)
索引.js
const SpellChecker = require('spellchecker');
module.exports = {
check: function() {
alert(SpellChecker.isMisspelled('keng'));
}
};
Run Code Online (Sandbox Code Playgroud)
包.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"
}
}
Run Code Online (Sandbox Code Playgroud)
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']
}
}
]
}
};
Run Code Online (Sandbox Code Playgroud)
在您的webpack.config.js
文件中,您指定要为 Node.js 构建此包:
target: 'node',
Run Code Online (Sandbox Code Playgroud)
webpack 决定保留require
调用,因为 Node.js 支持它们。如果您想在浏览器中运行它,target: 'web'
则应该使用。
归档时间: |
|
查看次数: |
6678 次 |
最近记录: |