在浏览器中访问Webpack捆绑库 [英] Accessing webpack bundled libraries in the browser
问题描述
我无法从浏览器访问Webpack捆绑库.
I'm having trouble accessing a webpack bundled library from the browser.
示例:我有一个课程Foo
// foo.js
"use strict";
export default class Foo {
constructor() {
var bar = "bar";
}
}
Foo
导入到src.js
// src.js
"use strict";
import Foo from "./foo.js";
webpack配置看起来像这样.条目为src.js
,输出文件为bundle.js
.
The webpack config looks like this. The entry is src.js
and the output file is bundle.js
.
// webpack.config.js
module.exports = {
entry: './src.js',
output: {
path: '.',
filename: 'bundle.js',
},
module: {
loaders: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader',
query: {
presets: ['es2015']
}
},
]
},
};
Webpack可以编译所有内容,并且我可以将其加载到HTML文件中.
Webpack compiles everything okay, and I'm able to load it into my HTML file.
<!-- index.html -->
<!DOCTYPE html>
<html>
<head>
<script src="bundle.js"></script>
<script type="text/javascript">
var x = new Foo();
console.log(x);
</script>
</head>
<body>
</body>
</html>
这是我遇到错误了.由于某些原因,捆绑的JS不会将Foo
类放入浏览器可以访问的命名空间中.
it's at this point that I'm getting the error. For some reason, the bundled JS doesn't put the Foo
class into a namespace the browser is able to access.
这是我在Firefox中遇到的错误:
This is the error I get in Firefox:
ReferenceError: Foo is not defined[Learn More]
我肯定不会在WebPack中进行一些配置,我敢肯定,但是到目前为止我仍然无法弄清楚.
There's some configuration in WebPack I'm not grokking, I'm sure of it, but I've so far not been able to figure it out.
推荐答案
要使此代码可重复使用,您需要告诉webpack您正在编写库.
To make this code re-usable, you need to tell webpack you are authoring a Library.
从Webpack中文档:
要使您的库可重复使用,请在webpack配置中添加库属性.
To make your library available for reuse, add library property in webpack configuration.
要创建您的库,请进行以下更改:
To create your library, make the following change:
module.exports = {
entry: './src.js',
output: {
path: '.',
filename: 'bundle.js',
library: 'fooLibrary', //add this line to enable re-use
},
...
要使用该库,您可以在其他脚本中引用它:
In order to use the library, you can then reference it in your other scripts:
<script type="text/javascript">
var x = new fooLibrary.Foo();
console.log(x);
</script>
这篇关于在浏览器中访问Webpack捆绑库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!