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

查看:33
本文介绍了如何从 <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天全站免登陆