Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

javascript - How to execute a webpack module from a <script>?

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

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

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.

I can include it,

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can set output.library in the configuration. From the docs:

output.library
If set, export the bundle as library. output.library is the name.

Use this, if you are writing a library and want to publish it as single file.

output.libraryTarget
Which format to export the library:

"var" - Export by setting a variable: var Library = xxx (default)

"this" - Export by setting a property of this: this["Library"] = xxx

"commonjs" - Export by setting a property of exports: exports["Library"] = xxx

"commonjs2" - Export by setting module.exports: module.exports = xxx

"amd" - Export to AMD (optionally named)

"umd" - Export to AMD, CommonJS2 or as property in root

Default: "var"

Then you will be able to do

myLibrary()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...