代码之家  ›  专栏  ›  技术社区  ›  nvcleemp

如何将与汇总绑定的库中的命名导出导入HTML页面?

  •  0
  • nvcleemp  · 技术社区  · 4 年前

    我可能只是对这应该如何工作的假设不正确,所以如果有人能告诉我在汇总配置中应该更改什么,或者我应该如何使用生成的包,我将不胜感激。

    让我来设定场景。我正在编写一个库,将其与汇总绑定在一起,然后想编写一些HTML页面,从该库导入一个命名的导出。它一直告诉我找不到指定的导出。

    为方便起见,我将这个问题归结为一个最小的例子:

    我的项目文件夹中有以下文件:

    • min-example.js :
    export function minExample(){
      return "can you find me?";
    }
    
    • package.json :
    {
      "name": "min-example",
      "version": "1.0.0",
      "description": "A minimal example of an issue with rollup",
      "scripts": {
        "build": "rollup -c"
      },
      "author": "nvcleemp",
      "license": "ISC",
      "devDependencies": {
        "rollup": "^2.58.0"
      }
    }
    
    • rollup.config.js
    export default [
      {
        input: "min-example.js",
        output: {
          file: `min-example.bundle.js`,
          name: "min-example",
          format: "umd"
        }
      }
    ];
    

    如果我跑 npm run build ,然后创建文件 min-example.bundle.js :

    (function (global, factory) {
      typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
      typeof define === 'function' && define.amd ? define(['exports'], factory) :
      (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global["min-example"] = {}));
    })(this, (function (exports) { 'use strict';
    
      function minExample(){
        return "can you find me?";
      }
    
      exports.minExample = minExample;
    
      Object.defineProperty(exports, '__esModule', { value: true });
    
    }));
    

    我希望我能以以下方式使用此文件:

    <!DOCTYPE html>
    <html>
    
    <head>
        <meta charset="utf-8">
        <title>Minimum example</title>
    </head>
    
    <body>
            <script type="module">
            import { minExample } from './min-example.bundle.js';
    
            console.log(minExample());
        </script>
    </body>
    
    </html>
    

    然而,正如我上面所说的,它抱怨找不到指定的导出 minExample .

    请注意,它在不使用汇总的情况下工作:

    <!DOCTYPE html>
    <html>
    
    <head>
        <meta charset="utf-8">
        <title>Minimum example</title>
    </head>
    
    <body>
            <script type="module">
            import { minExample } from './min-example.js';
    
            console.log(minExample());
        </script>
    </body>
    
    </html>
    
    0 回复  |  直到 4 年前
        1
  •  0
  •   nvcleemp    4 年前

    好的,再尝试一下错误,让我们找到一个解决方案。显然,输出格式应该是 es 而不是 umd ,所以文件 rollup.config.js 不得不改成

    export default [
      {
        input: "min-example.js",
        output: {
          file: `min-example.bundle.js`,
          name: "min-example",
          format: "es"
        }
      }
    ];
    

    所以我确实有一个错误的印象 umd 只是合并了 cjs .