我在从浏览器访问 webpack 捆绑库时遇到问题。
示例:我有一节课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
.
// 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 文件中。
<!-- 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
类到浏览器能够访问的命名空间中。
这是我在 Firefox 中遇到的错误:
ReferenceError: Foo is not defined[Learn More]
WebPack 中有一些配置我没有摸索过,我确信这一点,但到目前为止我还无法弄清楚。