gpt4 book ai didi

javascript - 是否可以混合捆绑模块和 JavaScript 模块

转载 作者:行者123 更新时间:2023-12-01 15:16:25 25 4
gpt4 key购买 nike

灵感来自 preact's "no build tools route" ,我最近创建了一个没有构建或捆绑过程的项目。从概念上讲,它看起来像这样(下面的伪代码)。
我依赖 react-button它使用例如microbundle解决preact通过 node_modules 导入文件夹。

// dependency 1: "preact-button" npm package (uses bundler)
import { h, Component, render } from 'preact';

const button = h('button', null, 'Click');
export default Button;
然后,我的应用程序需要 preact-button作为依赖。这只是一个 .html暂时存档。
<!doctype html>
<html>
<head>
<meta charset="utf-8"/>
<title>SO App</title>
<script type="module">
import { h, Component, render } from 'https://unpkg.com/preact?module';
import Button from "https://fantasycdn.com/preact-button?module"
</script>
</head>
<body>
</body>
</html>
但是,我的应用程序没有使用任何捆绑程序,因此导入了 preact-button的代码。如果我有一个捆绑器,这将不是问题,因为 import ... from "preact"将通过捆绑器解决。但是现在,利用 type="module"语法,这个全局模块名称不能再被导入。相反,会引发错误:
react-button.js:
Uncaught TypeError: Error resolving module specifier “preact”. Relative module specifiers must start with “./”, “../” or “/”.
作为 preact-button 的作者,但我想要的是我的模块:
  • 可以与捆绑器一起使用(如上所示)
  • 可以通过某种方式解决它的依赖关系(动态?)在 JavaScript 模块中使用

  • 由于 preact 在他们的网站上宣传这种方法,我快速浏览了他们的构建过程。它们有一个简单的优势,那就是它们不必处理任何类型的依赖关系(例如对等或常规),因为它们根本没有任何依赖关系。
    但是是否可以在没有繁重构建过程的情况下混合捆绑模块和 JavaScript 模块?甚至可能有一个普遍同意的方法吗?

    最佳答案

    请注意 UNPKG claims :

    ?module

    Expands all “bare” import specifiers in JavaScript modules to unpkg URLs. This feature is very experimental


    这意味着您的构建将由 UNPKG 转换和缓存为:
    import { h, Component, render } from 'https://unpkg.com/preact@^10.4.6?module';

    const button = h('button', null, 'Click');
    export default Button;
    作为对这一说法的确认,我检查了 ?module handle one of my bundled libraries on UNPKG ,并且它转换为:
    import { Parser, Grammar } from 'nearley';
    import moo from 'moo';
    进入:
    import { Parser, Grammar } from "https://unpkg.com/nearley@^2.19.1?module";
    import moo from "https://unpkg.com/moo@^0.5.1?module";
    假设您的 preact-button模块发布在 npm 上,当前在代码中使用裸导入说明符应该不是问题。

    关于javascript - 是否可以混合捆绑模块和 JavaScript 模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62934439/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com