问题描述
我试图理解,如何使用WebPack将我所有模块特定的JS源捆绑到一个文件中。对于这个示例,我只使用一个JS文件。
I'm trying to understand, how to use WebPack to bundle all my module specific JS source to a single file. For this sample I'm using just a single JS file.
通常我会像这样写我的JavaScript和HTML:
Normally I would write my JavaScript and HTML like this:
foo.js
var foo = function (className) {
this.className = null;
this.init(className)
}
foo.prototype = {
"init": function (className) {
this.className = className
},
"render": function () {
var o = document.createElement("span")
o.setAttribute("class", this.className)
o.textContent = "foo's className is " + this.className
return o
}
}
index.html
<html>
<head>
...
<script src="foo.js"></script>
</head>
<body>
...
<div id="foobar"></div>
<script>
;(function () {
var className = "bar"
var o = new foo(className)
document.getElementById("foobar").appendChild(o.render())
})()
</script>
...
</body>
</html>
大部分时间脚本部分由PHP应用程序注入,变量的值将来自某些后端代码。
Most times the script part gets injected by a PHP application and the value of the variable will come from some backend code.
现在我正在尝试将我的JS代码与WebPack捆绑在一起。 webpack.config.js 如下所示:
Now I'm trying to bundle my JS code with WebPack. The webpack.config.js looks like this:
module.exports = {
context: __dirname,
entry: {
bundle: [
"./src/foo.js"
]
},
output: {
filename: "dst/[name].js"
}
}
我更新 foo.js 文件:
...
module.exports = foo
现在我用 webpack -p ,然后我更改HTML以包含新的bundle.js并且需要 foo 。
index.html
<html>
<head>
...
<script src="dst/bundle.js"></script>
</head>
<body>
...
<div id="foobar"></div>
<script>
;(function () {
var foo = require("foo")
var className = "bar"
var o = new foo(className)
document.getElementById("foobar").appendChild(o.render())
})()
</script>
...
</body>
</html>
但现在我收到以下错误:
But now I just get the following error:
ReferenceError: requrie is not defined
var foo = requrie("foo")
如何使此代码与WebPack一起使用? WebPack是否是正确的工具?
How can I make this code work with WebPack? Is WebPack even the right tool for doing this?
推荐答案
我终于找到了解决方案。像这样更新 webpack.config.js :
I finally found the solution. Update the webpack.config.js like this:
module.exports = {
context: __dirname,
entry: {
"./src/foo.js"
]
},
output: {
library: "foo",
libraryTarget: "umd",
filename: "dst/[name].js"
}
}
这篇关于如何将变量传递给WebPack模块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!