Webpack构建后,在bundle.js中未定义导出的函数

时间:2019-07-13 21:16:02

标签: javascript webpack

我有由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始终是不确定的。

更新:

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

enter image description here

1 个答案:

答案 0 :(得分:0)

在webpack中,默认范围不是全局的。它在匿名函数中包含所有代码。要将您的库暴露给浏览器的全局范围,请use this answer

您的webpack配置如下:

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`,
        }),
    ],
};