【问题标题】:How to export a webpack-bundled function to global如何将 webpack 捆绑的函数导出到全局
【发布时间】:2020-03-09 17:31:52
【问题描述】:

我有一个 webpack 捆绑的 TypeScript 文件,它导出了我需要从全局使用的函数,例如:

// bundled.ts
import * as Excel from 'exceljs';
import { saveAs } from 'file-saver';

declare const $find: any;

export function configExport() {
    $('#ExportToExcelBtn').click( async () => {
        ...
        let dataItems = $find('ViewGrid').get_masterTableView().get_dataItems();
        ...
    });
}
// notBundled.js
configExport(); // does not exist in global window object

我一定没有正确阅读文档或其他内容,但我无法将 configExport 函数暴露/导出/提供/任何内容传递给 window。我研究了export-loaderexpose-loaderProvidePlugin,但我并不清楚我应该在这里做什么。

到目前为止,我已经在我的 webpack.config.js 中尝试过这样的事情:

    module: {
        rules: [
            {
                test: require.resolve("./Module/js/dist/bundled.js"),
                use: [{
                    loader: "expose-loader",
                    options: "bundledModuleCode",
                }]
            },

configExportbundledModuleCode 都没有像我想要的那样出现在 window 中。

  1. 甚至支持这个用例吗?
  2. 我该怎么做?

【问题讨论】:

  • 在您提供的代码中,我看不到任何地方 configExport 被导入。如果你不导入它,tree-shaking 会从你的包中完全消除它。如果你希望函数是全局的(我不希望它是全局的,因为你总是可以在任何需要的地方导入它),你必须将该函数附加到全局对象的属性上,如果你这样做使它成为一个出口(就像你所做的那样)似乎没有目的(对我来说)。
  • 我最终做了什么。

标签: javascript npm webpack export global


【解决方案1】:

我最终采用了一种类似于这里的方法:How do you explicitly set a new property on `window` in TypeScript?

// bundled.ts
import * as Excel from 'exceljs';
import { saveAs } from 'file-saver';

declare const $find: any;

// type configExport as window property
declare global {
    interface Window {
        configExport: any;
    }
}

// add configExport to window global
window.configExport = function() {
    ...
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-03
    • 1970-01-01
    • 1970-01-01
    • 2017-11-27
    • 1970-01-01
    • 2017-07-31
    相关资源
    最近更新 更多