【问题标题】:Import from a ParcelJS bundle从 ParcelJS 包导入
【发布时间】:2019-09-01 09:53:02
【问题描述】:

背景:

我创建了一个具有如下索引资源的库:

import {X} from '...'
import {Y} from '...'
import {Z} from '...'

export {X, Y, Z}

可以看出,这个文件收集了库的所有公共资源,并根据 ES6 模块标准将它们公开为可访问的入口点。当我使用 ParcelJs 从索引文件中创建一个名为 my-library.js 的包时,一切正常。

问题:

现在,我想从浏览器中使用该库,因此我使用以下脚本创建 index.html(请注意,此代码不是我项目的一部分,也不是我感兴趣的包含在包中。它只是用作时间测试):

<script type="module">
 import {X} from './my-library.js'
 console.log (X)
</script>

因此,控制台会发出以下错误消息:

Uncaught SyntaxError: The requested module './my-library.js' does
not provide an export named 'X'

有什么问题? ParcelJS 能否用于根据 ES6 规范捆绑库,以便稍后在使用来自外部脚本的导入语句时调用?

【问题讨论】:

    标签: javascript import importerror parceljs


    【解决方案1】:

    截至今天(2020 年 8 月),此功能仅在 Parcel2 中提供测试版。您可以通过以下方式获得想要的工作:

    1. 安装 Parcel2:npm i -g parcel@next
    2. 在你的项目中,安装 Babel 核心:npm i @babel/core --save-dev
    3. 在您的package.json 中添加以下配置:
      "main": "dist/legacy/index.js",
      "module": "dist/modern/index.js",
      "targets": {
        "module": {
          "engines": {
            "browsers": [
              "last 1 Chrome version"
            ]
          }
        },
        "main": {
          "engines": {
            "browsers": [
              "> 0.25%"
            ]
          }
        }
      },
    
    1. 构建您的代码:parcel build index.js

    dist/legacy/index.js 下的包使用 CommonJS,而dist/modern/index.js 下的包使用 ESM 语法。

    注意:将 JS 包捆绑到多个目标的另一种方法是 Microbundle

    【讨论】:

      猜你喜欢
      • 2018-12-05
      • 2022-01-06
      • 1970-01-01
      • 2019-06-27
      • 2019-03-12
      • 1970-01-01
      • 2020-11-29
      • 2018-09-27
      • 2016-07-17
      相关资源
      最近更新 更多