sam*_*len 13 javascript webpack babeljs
我无法从浏览器访问webpack捆绑库.
示例:我有一个班级 Foo
// foo.js
"use strict";
export default class Foo {
constructor() {
var bar = "bar";
}
}
Run Code Online (Sandbox Code Playgroud)
Foo 是进口的 src.js
// src.js
"use strict";
import Foo from "./foo.js";
Run Code Online (Sandbox Code Playgroud)
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']
}
},
]
},
};
Run Code Online (Sandbox Code Playgroud)
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>
Run Code Online (Sandbox Code Playgroud)
就在这时我才得到错误.由于某种原因,捆绑的JS不会将Foo类放入浏览器能够访问的命名空间中.
这是我在Firefox中遇到的错误:
ReferenceError: Foo is not defined[Learn More]
WebPack中有一些配置我不是很喜欢,我很确定,但到目前为止我还没弄清楚.
Cla*_*ies 24
要使此代码可重用,您需要告诉webpack您正在创建一个库.
从webpack 文档:
要使您的库可以重用,请在webpack配置中添加库属性.
要创建库,请进行以下更改:
module.exports = {
entry: './src.js',
output: {
path: '.',
filename: 'bundle.js',
library: 'fooLibrary', //add this line to enable re-use
},
...
Run Code Online (Sandbox Code Playgroud)
为了使用该库,您可以在其他脚本中引用它:
<script type="text/javascript">
var x = new fooLibrary.Foo();
console.log(x);
</script>
Run Code Online (Sandbox Code Playgroud)