我有一个由Webpack管理的构建过程。它将所有文件捆绑在一起并生成一个单独的bundle.js
文件。这是非常典型的模式。
但是,当我在网页中包含bundle.js
文件时,“导出的默认函数未定义”。为什么我无法从网页上的全局范围访问该导出函数?
这是我的Webpack配置:
const path = require('path');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
module.exports = {
entry: './src/js/index.js',
output: {
path: path.resolve('dist'),
filename: 'bundle.js',
},
performance: {
hints: false,
},
resolve: {
modules: ['node_modules', path.join(__dirname, 'src'), 'assets'],
},
module: {
rules: [
{
test: /\.(sa|sc|c)ss$/,
use: [MiniCssExtractPlugin.loader, 'css-loader', 'sass-loader'],
},
{
test: /\.js$/,
exclude: /node_modules/,
use: 'babel-loader',
},
{
test: /\.(eot|svg|ttf|woff|woff2)$/,
use: 'file-loader',
},
],
},
plugins: [
new MiniCssExtractPlugin({
filename: `bundle.css`,
}),
],
};
这里是一个简化的src/js/index.js
文件:
import util from './util';
import as dependency from 'external-library';
import EventEmitter from 'events';
/**
* MyLibrary module
* @module MyLibrary
* @class
* @param {MyLibraryOptions} options - Options to initialize the module with
* @returns {Object} MyLibrary instance
*/
export default function MyLibrary(options) {
if (!(this instanceof MyLibrary)) {
return new MyLibrary(options);
}
//...Do a bunch of stuff.
}
我们的目标是将bundle.js
包含在网页中,并在脚本标签中访问,例如:
var instance = new MyLibrary({option_1: value, ...})
然而,每次我这样做时,MyLibrary
总是未定义的。
更新:
添加了 library
属性后,MyLibrary
不再是未定义的,但我无法调用它。现在它是一个模块。
![enter image description here](https://istack.dev59.com/ESdq7.webp)
module.exports = {
entry: './src/js/index.js',
output: {
library: 'MyLibrary',
libraryTarget: 'umd',
libraryExport: 'default',
path: path.resolve('dist'),
filename: 'bundle.js',
}
...
script
标签包含了我的 JS 文件(在我的情况下是bundle.js
)。 - calbear47