在 HTML 中内联 ECMAScript module

IT技术 javascript html ecmascript-6 es6-modules
2021-03-07 02:54:19

我一直在试验最近添加到浏览器的新的原生 ECMAScript module支持终于能够直接、干净地从 JavaScript 导入脚本是一件令人愉快的事情。

     /example.html 🔍     
<script type="module">
  import {example} from '/example.js';

  example();
</script>
     /example.js     
export function example() {
  document.body.appendChild(document.createTextNode("hello"));
};

但是,这只允许我导入由单独的外部JavaScript 文件定义的module我通常更喜欢内联一些用于初始渲染的脚本,因此它们的请求不会阻塞页面的其余部分。对于传统的非正式结构的库,它可能如下所示:

     /inline-traditional.html 🔍     
<body>
<script>
  var example = {};

  example.example = function() {
    document.body.appendChild(document.createTextNode("hello"));
  };
</script>
<script>
  example.example();
</script>

但是,天真地内联module文件显然是行不通的,因为它会删除用于将module标识为其他module的文件名。HTTP/2 服务器推送可能是处理这种情况的规范方式,但它仍然不是所有环境中的一种选择。

是否可以使用 ECMAScript module执行等效转换?

a 有什么办法可以<script type="module">在同一个文档中导入另一个导出的module?


我想这可以通过允许脚本指定文件路径来工作,并且表现得好像它已经从路径下载或推送一样。

     /inline-name.html 🔍     
<script type="module" name="/example.js">
  export function example() {
    document.body.appendChild(document.createTextNode("hello"));
  };
</script>

<script type="module">
  import {example} from '/example.js';

  example();
</script>

或者可能使用完全不同的参考方案,例如用于本地 SVG 参考:

     /inline-id.html 🔍     
<script type="module" id="example">
  export function example() {
    document.body.appendChild(document.createTextNode("hello"));
  };
</script>
<script type="module">
  import {example} from '#example';

  example();
</script>

但是这些假设都没有实际工作,而且我还没有看到替代方案。

4个回答

一起破解我们自己的 import from '#id'

本机不支持内联脚本之间的导出/导入,但为我的文档编写一个实现是一个有趣的练习。Code-golfed 到一个小块,我这样使用它:

<script type="module" data-info="https://stackoverflow.com/a/43834063">let l,e,t
='script',p=/(from\s+|import\s+)['"](#[\w\-]+)['"]/g,x='textContent',d=document,
s,o;for(o of d.querySelectorAll(t+'[type=inline-module]'))l=d.createElement(t),o
.id?l.id=o.id:0,l.type='module',l[x]=o[x].replace(p,(u,a,z)=>(e=d.querySelector(
t+z+'[type=module][src]'))?a+`/* ${z} */'${e.src}'`:u),l.src=URL.createObjectURL
(new Blob([l[x]],{type:'application/java'+t})),o.replaceWith(l)//inline</script>

<script type="inline-module" id="utils">
  let n = 1;
  
  export const log = message => {
    const output = document.createElement('pre');
    output.textContent = `[${n++}] ${message}`;
    document.body.appendChild(output);
  };
</script>

<script type="inline-module" id="dogs">
  import {log} from '#utils';
  
  log("Exporting dog names.");
  
  export const names = ["Kayla", "Bentley", "Gilligan"];
</script>

<script type="inline-module">
  import {log} from '#utils';
  import {names as dogNames} from '#dogs';
  
  log(`Imported dog names: ${dogNames.join(", ")}.`);
</script>

取而代之的是<script type="module">,我们需要使用自定义类型(如<script type="inline-module">. 这可以防止浏览器尝试自己执行它们的内容,将它们留给我们处理。该脚本(以下完整版)查找inline-module文档中的所有脚本元素,并将它们转换为具有我们想要的行为的常规脚本module元素。

内联脚本不能直接相互导入,所以我们需要给脚本提供可导入的 URL。我们blob:为它们中的每一个生成一个URL,包含它们的代码,并将src属性设置为从该 URL 运行而不是内联运行。这些blob:URL 就像来自服务器的普通 URL 一样,因此它们可以从其他module导入。每次我们看到后续inline-module尝试从 导入时'#example'我们已转换example的 ID在哪里inline-module,我们都会修改该导入以从blob:URL导入这维护了module应该具有的一次性执行和引用重复数据删除。

<script type="module" id="dogs" src="blob:https://example.com/9dc17f20-04ab-44cd-906e">
  import {log} from /* #utils */ 'blob:https://example.com/88fd6f1e-fdf4-4920-9a3b';

  log("Exporting dog names.");

  export const names = ["Kayla", "Bentley", "Gilligan"];
</script>

module脚本元素的执行总是推迟到文档被解析之后,所以我们不必担心尝试支持传统脚本元素在文档仍在解析时修改文档的方式。

export {};

for (const original of document.querySelectorAll('script[type=inline-module]')) {
  const replacement = document.createElement('script');

  // Preserve the ID so the element can be selected for import.
  if (original.id) {
    replacement.id = original.id;
  }

  replacement.type = 'module';

  const transformedSource = original.textContent.replace(
    // Find anything that looks like an import from '#some-id'.
    /(from\s+|import\s+)['"](#[\w\-]+)['"]/g,
    (unmodified, action, selector) => {
      // If we can find a suitable script with that id...
      const refEl = document.querySelector('script[type=module][src]' + selector);
      return refEl ?
        // ..then update the import to use that script's src URL instead.
        `${action}/* ${selector} */ '${refEl.src}'` :
        unmodified;
    });

  // Include the updated code in the src attribute as a blob URL that can be re-imported.
  replacement.src = URL.createObjectURL(
    new Blob([transformedSource], {type: 'application/javascript'}));

  // Insert the updated code inline, for debugging (it will be ignored).
  replacement.textContent = transformedSource;

  original.replaceWith(replacement);
}

警告:这个简单的实现不处理在解析初始文档后添加的脚本元素,也不允许从文档中出现在它们之后的其他脚本元素导入脚本元素。如果文档中同时具有moduleinline-module脚本元素,则它们的相对执行顺序可能不正确。源代码转换是使用粗略的正则表达式执行的,该正则表达式不会处理某些边缘情况,例如 ID 中的句点。

您可以进一步使用正则表达式 /(from|import)\s+('|")(#[\w\-]+)\2/g
2021-04-22 02:54:19
你在 github 或 npm 中有吗?
2021-04-25 02:54:19
我想知道扩展的自定义元素是否可能 <script is="inline-module" type="module" id="a"></script>
2021-04-29 02:54:19
我使用这个查询选择器解决了“无句点”问题: const refEl = document.querySelector(`script[type=module][src][id="${selector}"]`); 我还让选择器寻找更通用的: /(from\s+|import\s+)['"](.*)['"]/g
2021-05-17 02:54:19

这对于服务工作者来说是可能的。

由于 service worker 应该在它能够处理页面之前安装,这需要有一个单独的页面来初始化一个 worker 以避免鸡/蛋问题 - 或者当一个 worker 准备好时可以重新加载页面。

例子

这是一个演示,应该可以在支持原生 ES module和async..await(即 Chrome)的现代浏览器中运行

索引.html

<html>
  <head>
    <script>
      (async () => {
        try {
          const swInstalled = await navigator.serviceWorker.getRegistration('./');

          await navigator.serviceWorker.register('sw.js', { scope: './' })

          if (!swInstalled) {
            location.reload();
          }
        } catch (err) {
          console.error('Worker not registered', err);
        }
      })();
    </script>
  </head>

  <body>
    World,

    <script type="module" data-name="./example.js">
      export function example() {
        document.body.appendChild(document.createTextNode("hello"));
      };
    </script>

    <script type="module">
      import {example} from './example.js';

      example();
    </script>
  </body>
</html>

sw.js

self.addEventListener('fetch', e => {
  // parsed pages
  if (/^https:\/\/run.plnkr.co\/\w+\/$/.test(e.request.url)) {
    e.respondWith(parseResponse(e.request));
  // module files
  } else if (cachedModules.has(e.request.url)) {
    const moduleBody = cachedModules.get(e.request.url);
    const response = new Response(moduleBody,
      { headers: new Headers({ 'Content-Type' : 'text/javascript' }) }
    );
    e.respondWith(response);
  } else {
    e.respondWith(fetch(e.request));
  }
});

const cachedModules = new Map();

async function parseResponse(request) {
  const response = await fetch(request);
  if (!response.body)
    return response;

  const html = await response.text(); // HTML response can be modified further
  const moduleRegex = /<script type="module" data-name="([\w./]+)">([\s\S]*?)<\/script>/;
  const moduleScripts = html.match(new RegExp(moduleRegex.source, 'g'))
    .map(moduleScript => moduleScript.match(moduleRegex));

  for (const [, moduleName, moduleBody] of moduleScripts) {
    const moduleUrl = new URL(moduleName, request.url).href;
    cachedModules.set(moduleUrl, moduleBody);
  }
  const parsedResponse = new Response(html, response);
  return parsedResponse;
}

脚本主体被缓存(Cache也可以使用本机)并为相应的module请求返回。

顾虑

  • 在性能、灵活性、可靠性和浏览器支持方面,这种方法不如使用 Webpack 或 Rollup 等捆绑工具构建和分块的应用程序——尤其是在阻塞并发请求是主要关注点的情况下。

  • 内联脚本会增加带宽使用。当脚本加载一次并被浏览器缓存时,这自然可以避免。

  • 内联脚本不是module化的,并且与 ECMAScript module的概念相矛盾(除非它们是由服务器端模板从真实module生成的)。

  • Service Worker 初始化应在单独的页面上执行,以避免不必要的请求。

  • 该解决方案仅限于单个页面并且不<base>考虑。

  • 正则表达式仅用于演示目的。当像上面的例子那样使用时,它可以执行页面上可用的任意 JavaScript 代码parse5应该使用类似的经过验证的库(它会导致性能开销,并且仍然可能存在安全问题)。永远不要使用正则表达式来解析 DOM

这会更粗暴,所以我可能不推荐它,但是如果我们重写 index.html 那么这给了我们一种方法来同步检测 service worker 是否已加载,通过让它向页面添加一些属性,从而防止其他任何东西第一次加载/运行不当,而不是等待异步 getRegistration 结果。
2021-04-19 02:54:19
是的。location.reload()味道不好,但说明了这个问题。通常,我会建议为入口点//?serviceWorkerInstalledOrNotSupported入口点设置单独的服务器响应
2021-04-30 02:54:19
@Melab 你能澄清一下吗?安装在<script>.
2021-05-02 02:54:19
如何安装 Service Worker?这些是通过 HTTP 交付的。
2021-05-03 02:54:19
我喜欢它!非常聪明。
2021-05-16 02:54:19

我不相信这是可能的。

对于内联脚本,您会使用一种更传统的module化代码方法,例如您使用对象字面量演示的命名空间。

使用webpack,您可以进行代码拆分,您可以使用它在页面加载时抓取非常少的代码块,然后根据需要逐步抓取其余代码。Webpack 还具有允许您在更多环境中使用module语法(以及大量其他 ES201X 改进)的优势,而不仅仅是 Chrome Canary。

使用这篇文章调整了Jeremy 的答案,以防止脚本执行

<script data-info="https://stackoverflow.com/a/43834063">
// awsome guy on [data-info] wrote 90% of this but I added the mutation/module-type part

let l,e,t='script',p=/(from\s+|import\s+)['"](#[\w\-]+)['"]/g,x='textContent',d=document,s,o;

let evls = event => (
  event.target.type === 'javascript/blocked', 
  event.preventDefault(),
  event.target.removeEventListener( 'beforescriptexecute', evls ) )

;(new MutationObserver( mutations => 
  mutations.forEach( ({ addedNodes }) => 
    addedNodes.forEach( node => 
      ( node.nodeType === 1 && node.matches( t+'[module-type=inline]' )
      && ( 
        node.type = 'javascript/blocked',
        node.addEventListener( 'beforescriptexecute', evls ),
      
        o = node,
        l=d.createElement(t),
        o.id?l.id=o.id:0,
        l.type='module',
        l[x]=o[x].replace(p,(u,a,z)=>
          (e=d.querySelector(t+z+'[type=module][src]'))
            ?a+`/* ${z} */'${e.src}'`
            :u),
        l.src=URL.createObjectURL(
          new Blob([l[x]],
          {type:'application/java'+t})),
        o.replaceWith(l)
      )//inline

) ) )))
.observe( document.documentElement, {
  childList: true,
  subtree: true
} )

// for(o of d.querySelectorAll(t+'[module-type=inline]'))
//   l=d.createElement(t),
//   o.id?l.id=o.id:0,
//   l.type='module',
//   l[x]=o[x].replace(p,(u,a,z)=>
//     (e=d.querySelector(t+z+'[type=module][src]'))
//       ?a+`/* ${z} */'${e.src}'`
//       :u),
//   l.src=URL.createObjectURL(
//     new Blob([l[x]],
//     {type:'application/java'+t})),
//   o.replaceWith(l)//inline</script>

我希望这可以解决动态脚本附加问题(使用 MutationObserver),vs 代码而不是语法突出显示(保留类型 = module),我想使用相同的 MutationObserver 可以在添加导入的 id 后执行脚本到 DOM。

请告诉我这是否有问题!