Javascript 生成Web包后,bundle.js中未定义导出的函数

Javascript 生成Web包后,bundle.js中未定义导出的函数,javascript,webpack,Javascript,Webpack,我有一个由Webpack管理的构建过程。它将我的所有文件打包并生成一个bundle.js文件。非常典型的模式 但是,当我在网页中包含该文件bundle.js时,导出的默认函数未定义。为什么我不能从网页的全局作用域访问导出的函数 这是我的网页配置: const path=require('path'); const MiniCssExtractPlugin=require('mini-css-extract-plugin'); module.exports={ 条目:'./src/js/index

我有一个由Webpack管理的构建过程。它将我的所有文件打包并生成一个
bundle.js
文件。非常典型的模式

但是,当我在网页中包含该文件
bundle.js
时,导出的默认函数未定义。为什么我不能从网页的全局作用域访问导出的函数

这是我的网页配置:

const path=require('path');
const MiniCssExtractPlugin=require('mini-css-extract-plugin');
module.exports={
条目:'./src/js/index.js',
输出:{
path:path.resolve('dist'),
文件名:“bundle.js”,
},
性能:{
提示:错,
},
决心:{
模块:['node_modules',path.join('src'),'assets'],
},
模块:{
规则:[
{
测试:/\(sa|sc|c)ss$/,
用法:[MiniCssExtractPlugin.loader,'css loader','sass loader'],
},
{
测试:/\.js$/,,
排除:/node_模块/,
使用“babel loader”,
},
{
测试:/\(eot | svg | ttf | woff | woff2)$/,
使用“文件加载器”,
},
],
},
插件:[
新的MinicsSextract插件({
文件名:`bundle.css`,
}),
],
};
下面是一个简化的
src/js/index.js

从“/util”导入util;
作为依赖项从“外部库”导入;
从“事件”导入EventEmitter;
/**
*我的图书馆模块
*@modulemylibrary
*@级
*@param{MyLibraryOptions}options-用于初始化模块的选项
*@returns{Object}MyLibrary实例
*/
导出默认函数MyLibrary(选项){
如果(!(MyLibrary的此实例)){
返回新的MyLibrary(选项);
}
//…做一大堆事。
}
目标是在网页上包含
bundle.js
,并在脚本标记中访问,例如:

var instance=newmylibrary({option_1:value,…})
然而,当我这样做时,
MyLibrary
总是未定义的

更新:

在webpack配置中添加了
library
属性之后,
MyLibrary
不是未定义的,但是我不能调用它。它现在是一个模块

更新2-->解决方案:

module.exports = {
    entry: './src/js/index.js',
    output: {
        library: 'MyLibrary',
        libraryTarget: 'umd',
        libraryExport: 'default',
        path: path.resolve('dist'),
        filename: 'bundle.js',
   }
...

在Web包中,默认范围不是全局范围。它包含匿名函数中的所有代码。要将库公开到浏览器的全局范围,请执行以下操作:

您的网页包配置如下所示:

const path = require('path');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');

module.exports = {
    entry: './src/js/index.js',
    output: {
        library: 'MyLibrary',
        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`,
        }),
    ],
};

最后一段代码是否运行浏览器?@CalderWhite是的,我收到一个错误,MyLibrary未定义。这非常接近……但现在
MyLibrary
只是一个模块。我无法调用
新MyLibrary()
。签出我的更新问题。@calbear47你是说你必须调用类似于
MyLibrary.MyLibrary
?是的,就是这样。我只想调用MyLibrary()我相信libraryTarget与您所追求的相关。请尝试我的编辑,如果这不起作用,我们可以从以下文档中进一步了解:。@calbear47^^^^