以HTML格式内联ECMAScript模块

46 html javascript ecmascript-6 es6-modules

我一直在尝试最近添加到浏览器中的新的原生ECMAScript模块支持.最终能够直接从JavaScript轻松导入脚本是令人愉快的.

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

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

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

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

  example.example = function() {
    document.body.appendChild(document.createTextNode("hello"));
  };
</script>
<script>
  example.example();
</script>
Run Code Online (Sandbox Code Playgroud)

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

是否可以使用ECMAScript模块执行等效转换?有没有办法<script type="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>
Run Code Online (Sandbox Code Playgroud)

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

     /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>
Run Code Online (Sandbox Code Playgroud)

但这些假设中的任何一个都没有实际起作用,而且我还没有看到一个替代方案.

小智 20

一起黑客攻击我们自己 import from '#id'

内联脚本之间的导出/导入本身不受支持,但将文档的实现混合在一起是一项有趣的练习.代码高尔夫球到一个小块,我使用它像这样:

<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>
Run Code Online (Sandbox Code Playgroud)

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

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

<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>
Run Code Online (Sandbox Code Playgroud)

模块脚本元素的执行总是延迟到解析文档之后,因此我们不必担心尝试支持传统脚本元素在仍然被解析时修改文档的方式.

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);
}
Run Code Online (Sandbox Code Playgroud)

警告:此简单实现不处理在解析初始文档后添加的脚本元素,或允许脚本元素从文档中的后续脚本元素导入.如果文档中同时包含moduleinline-module脚本元素,则它们的相对执行顺序可能不正确.使用原始正则表达式执行源代码转换,该正则表达式不会处理某些边缘情况,例如ID中的句点.

  • 您可以进一步将正则表达式打入`/(from | import)\ s +('|“)(#[\ w \-] +)\ 2 / g` (2认同)

Est*_*ask 8

服务人员可以做到这一点.

由于服务工作者应该在能够处理页面之前安装,因此需要有一个单独的页面来初始化工作者以避免鸡/蛋问题 - 或者当工作人员准备好时页面可以重新加载.

这是一个应该在支持本机ES模块和async..await(即Chrome)的浏览器中可用的示例:

的index.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>
Run Code Online (Sandbox Code Playgroud)

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;
}
Run Code Online (Sandbox Code Playgroud)

正在缓存脚本主体(本机Cache也可以使用)并返回各个模块请求.

关注

  • 在性能,灵活性,可靠性和浏览器支持方面,该方法不如使用捆绑工具(如Webpack或Rollup)构建和分块的应用程序 - 特别是如果阻塞并发请求是主要关注点.

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

  • 内联脚本不是模块化的,与ES模块的概念相矛盾(除非它们是由服务器端模板从实际模块生成的).

  • 应在单独的页面上执行服务工作者初始化,以避免不必要的请求.

  • 解决方案仅限于单个页面,不<base>考虑.

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


bmc*_*ney 3

我不相信这是可能的。

对于内联脚本,您只能使用一种更传统的模块化代码方法,例如您使用对象文字演示的命名空间。

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