【问题标题】:Exporting a function to the front-end with Webpack使用 Webpack 将函数导出到前端
【发布时间】:2021-05-21 23:54:10
【问题描述】:

我是 webpack 的新手,正在尝试建立一个基本的实现。

我有一个文件script.js,里面有一些函数

scripts.js

export foo = () => {
   console.log('foo')
}

export bar = () => {
   console.log('bar')
}

我正在尝试将它添加到我的 webpack bundle.js 以便我可以在标记中使用这些功能。

webpack.confi.js

const path = require('path')

module.exports = {
    entry: './index.js',
    output: {
        path: path.resolve(__dirname, 'dist'),
        filename: 'bundle.js'
    }
}

我的index.js 看起来像这样:

import * as scripts from './scripts.js';

这在 node 中有效,因为如果我将 console.log(scripts.foo()) 添加到 index.jsimport 行下方,我可以观察控制台日志。

但如果我尝试在我的 标记 中调用 foo(),我会收到一个未定义的错误:

Uncaught ReferenceError: foo is not defined

index.html

<script src="./dist/bundle.js"></script>
<script>

    scripts.foo(); // throws undefined error

</script>

我错过了什么?

【问题讨论】:

  • Webpack 和模块的重点是不污染全局范围,因此scripts 对内联的&lt;script&gt; 标签不可见。如果你需要这个,你可以分配给窗口。在 scripts.js 中:window.scripts = { foo: // ... 非常谨慎地使用它,可能只用于库命名空间(例如 jQuery)之类的东西
  • @CertainPerformance 好的,我想我明白了。但是在这种情况下, webpack 的意义何在。如果我通过 webpack 导入的库没有暴露给标记中的给定网页,那么我不确定我是否得到了用例
  • 用模块编写所有你的脚本,与Webpack集成。例如,添加到index.jsscripts.foo()
  • 但是scripts.foo() 通过import 语句有效地添加到index.js - 然后在运行weback 之后,我可以看到这些函数在eval 语句中添加到bundle.js,其中通过脚本标签 src 全局引用。按理说这些函数应该暴露给下面的所有 JS,但它们不是
  • 整个捆绑包都在一个 IIFE 中。有点像(() =&gt; { const scripts = (() =&gt; { /* code of library */ })(); /* index.js starts */ scripts.foo(); })(); 它的内部没有暴露在外面。这就是为什么理论上你可以在页面上拥有任意数量的单独 Webpack 包,而不会导致全局变量冲突。

标签: javascript node.js npm webpack ecmascript-6


【解决方案1】:

整个 Webpack 的捆绑输出都在一个 IIFE 中。例如,一个只有两个模块的脚本,一个从另一个导入:

export default 'someVar';
import someVar from './someVar';
console.log(someVar);

产生以下输出:

/******/ (function(modules) { // webpackBootstrap
/******/    // The module cache
/******/    var installedModules = {};
/******/
/******/    // The require function
/******/    function __webpack_require__(moduleId) {
/******/
/******/        // Check if module is in cache
/******/        if(installedModules[moduleId]) {
/******/            return installedModules[moduleId].exports;
/******/        }
/******/        // Create a new module (and put it into the cache)
/******/        var module = installedModules[moduleId] = {
/******/            i: moduleId,
/******/            l: false,
/******/            exports: {}
/******/        };
/******/
/******/        // Execute the module function
/******/        modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/        // Flag the module as loaded
/******/        module.l = true;
/******/
/******/        // Return the exports of the module
/******/        return module.exports;
/******/    }
/******/
/******/
/******/    // expose the modules object (__webpack_modules__)
/******/    __webpack_require__.m = modules;
/******/
/******/    // expose the module cache
/******/    __webpack_require__.c = installedModules;
/******/
/******/    // define getter function for harmony exports
/******/    __webpack_require__.d = function(exports, name, getter) {
/******/        if(!__webpack_require__.o(exports, name)) {
/******/            Object.defineProperty(exports, name, { enumerable: true, get: getter });
/******/        }
/******/    };
/******/
/******/    // define __esModule on exports
/******/    __webpack_require__.r = function(exports) {
/******/        if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/            Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/        }
/******/        Object.defineProperty(exports, '__esModule', { value: true });
/******/    };
/******/
/******/    // create a fake namespace object
/******/    // mode & 1: value is a module id, require it
/******/    // mode & 2: merge all properties of value into the ns
/******/    // mode & 4: return value when already ns object
/******/    // mode & 8|1: behave like require
/******/    __webpack_require__.t = function(value, mode) {
/******/        if(mode & 1) value = __webpack_require__(value);
/******/        if(mode & 8) return value;
/******/        if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
/******/        var ns = Object.create(null);
/******/        __webpack_require__.r(ns);
/******/        Object.defineProperty(ns, 'default', { enumerable: true, value: value });
/******/        if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
/******/        return ns;
/******/    };
/******/
/******/    // getDefaultExport function for compatibility with non-harmony modules
/******/    __webpack_require__.n = function(module) {
/******/        var getter = module && module.__esModule ?
/******/            function getDefault() { return module['default']; } :
/******/            function getModuleExports() { return module; };
/******/        __webpack_require__.d(getter, 'a', getter);
/******/        return getter;
/******/    };
/******/
/******/    // Object.prototype.hasOwnProperty.call
/******/    __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/    // __webpack_public_path__
/******/    __webpack_require__.p = "";
/******/
/******/
/******/    // Load entry module and return exports
/******/    return __webpack_require__(__webpack_require__.s = "./src/index.js");
/******/ })
/************************************************************************/
/******/ ({

/***/ "./src/index.js":
/*!**********************!*\
  !*** ./src/index.js ***!
  \**********************/
/*! no exports provided */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _someVar__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./someVar */ "./src/someVar.js");

console.log(_someVar__WEBPACK_IMPORTED_MODULE_0__["default"]);

/***/ }),

/***/ "./src/someVar.js":
/*!************************!*\
  !*** ./src/someVar.js ***!
  \************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony default export */ __webpack_exports__["default"] = ('someVar');

/***/ })

/******/ });

简化后如下所示:

(function (modules) {
    // (code that manages the modules)
})
    ({

        "./src/index.js":
            (function (module, __webpack_exports__, __webpack_require__) {
                __webpack_require__.r(__webpack_exports__);
/* harmony import */ var _someVar__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./someVar */ "./src/someVar.js");
                console.log(_someVar__WEBPACK_IMPORTED_MODULE_0__["default"]);
            }),
        "./src/someVar.js":
            (function (module, __webpack_exports__, __webpack_require__) {
                __webpack_require__.r(__webpack_exports__);
/* harmony default export */ __webpack_exports__["default"] = ('someVar');

            })

    });

someVar 未全局公开;它在 Webpack 生成的 IIFE 中。因此,页面上的内联 &lt;script&gt; 标记不可见。

出于类似的原因,以下代码不会导致任何全局污染:

((modules) => {
  const getModule = (moduleName) => modules[moduleName];
  modules.main(getModule);
})({
  main: (getModule) => console.log('main running can see ' + getModule('foo')),
  foo: 'foo content'
});

这是一个好事。如果模块在全球范围内公开,命名冲突可能会很频繁,尤其是对于具有大量具有不同功能的独立脚本的大型网站。

将所有依赖于库的代码也放入模块中,例如,将我们的index.js 更改为

import * as scripts from './scripts.js';
scripts.foo();

【讨论】:

    【解决方案2】:

    你必须在你的 webpack 配置中添加 output.library 选项。 看这篇文章:https://webpack.js.org/guides/author-libraries/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-13
      • 2019-05-17
      相关资源
      最近更新 更多