Webpack导出功能 [英] Webpack export function

查看:191
本文介绍了Webpack导出功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些js文件,每个文件都是一个具有唯一名称的standonlone函数,我想将所有这些文件打包在一个包中所以我这样做了代码

I have some js files, and each file is a standonlone function with unique name, And I want to pack all this files in one bundle So I do this code

module.exports = {
    entry: {
        app:[
            './file1.js',
            './file2.js',
            './file3.js',
            './file4.js'
        ],
    },
    output: {
        path: './dist/',
        filename: '[name].bundle.js'
    }
};

这是工作,我有我的捆绑文件.dist / app.bundle.js

that's work and I have my bundle file ".dist/app.bundle.js"

现在我在HTML正文中有一些js代码需要调用bundle中的函数,
如果我尝试调用函数functionA(在file1中有所不同) .js)我在浏览器控制台中收到此消息

Now I have some js code in the HTML body that need to call functions in the bundle, If I try to call function "functionA" (that is difined in file1.js) I get this message in browser console

Uncaught ReferenceError: functionA is not defined

问题是如何从包中导出我的函数以在我的HTML代码中导入它?

The question is how can I export my functions from bundle to import it in my HTML code ?

推荐答案

从入口点文件导出内容不会使它们可用于全局范围。你有两个选择 - 显式地将函数添加到窗口对象,如下所示:

Exporting things from an entry point file does not make them available to the global scope. You have two options - either explicitly add the functions to the window object, like so:

window.functionA = functionA;

或者将您的构建配置为输出为库:

Or configure your build to output as a library:

// webpack.config.js - abridged
module.exports = {
    output: {
        library: "myModule",
        libraryTarget: "umd"
    }
};

我不知道后者如何与您的入口点设置为文件数组进行交互 - 您可能必须创建一个导入所有函数的单个条目文件( main.js 或其他东西),然后重新导出包含在对象中的函数,或类似的东西。

I don't know how the latter interacts with your entry point being set to an array of files - you may have to make a single entry file (main.js or something) that imports all of the functions and then re-exports them contained in an object, or something like that.

这篇关于Webpack导出功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆