如何从< script>执行webpack模块? [英] How to execute a webpack module from a <script>?

查看:45
本文介绍了如何从< script>执行webpack模块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了一个看起来像这样的ES6模块:

I've written an ES6 module that looks something like this:

export default function({makeCurrentVerUrl, verUrl, fileServer, downloadTokenType, appId}) {
    ...
}

由webpack编译时,看起来像这样:

When compiled by webpack, it looks something like this:

webpackJsonp([5,7],[
/* 0 */
/***/ function(module, exports) {

    'use strict';

    Object.defineProperty(exports, "__esModule", {
        value: true
    });

    exports.default = function (_ref) {
        var makeCurrentVerUrl = _ref.makeCurrentVerUrl;
        var verUrl = _ref.verUrl;
        var fileServer = _ref.fileServer;
        var downloadTokenType = _ref.downloadTokenType;
        var appId = _ref.appId;

        ...
    };

/***/ }
]);

哪个很棒,但是我不确定如何运行此文件并调用默认函数.

Which is great, but I'm not sure how to run this file and call my default function.

我可以包括它,

<script src="/path/to/script.js"></script>

我相信这将自动运行它,但是如何从浏览器中调用在其中定义的函数呢?我的浏览器中未定义 require .

Which I believe will run it automatically, but how can I call the functions I've defined in it from the browser? require is not defined in my browser.

推荐答案

因此,无需更改 output.library (假设您不想全球化一切)只是将所需的功能附加到 window .例如

So the easiest way to do this without changing output.library (assuming you don't want to globalize everything) is to just attach your needed functions to the window. e.g.

// entry-point.js
import foo from './scripts/foo.js';
window.foo = foo;

或者,如果您要将一堆东西附加到 window (不只是 default )上,则可以执行以下操作:

Or if you want to attach a whole bunch of stuff to the window (not just default), you can do something like:

Object.assign(window, require('./scripts/somelib.js'));

您还可以查看 bundle-loader ,内置的Webpack功能 require.context 或动态的 import() s如果要在运行时包括一些脚本.

You can also take a look at bundle-loader, the built-in webpack feature require.context or dynamic import()s if you want to include some scripts at run-time.

这篇关于如何从&lt; script&gt;执行webpack模块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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