0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Google Apps Script で ES Modules を使う方法

Posted at

これは何?

ES Module で作成されているライブラリを利用するときに困ったのでメモ。
読み込みたいモジュールが DOMContentLoaded 後に使用したいものだったので、 Promise で合成している。ただ <script type="module"> を使えば十分だったかもしれない。

作成が必要なファイル一覧

ファイル名 説明
main.gs
index.html
libLoader.js.html ES Module コードを動的に読み込むためのコード
index.js.html EM Module を利用したいコード
Lib_js.html 読み込みたい MS Module コード

Codes

main.gs
'use strict';

function doGet() {
  return HtmlService
    .createTemplateFromFile('index')
    .evaluate();
}

/**
 * 
 * @param {string} filename
 * @returns {string} Html code
 */
function include(filename) {
  return HtmlService.createHtmlOutputFromFile(filename).getContent();
}

/**
 * 
 * @returns {string} javascript code
 */
function api_loadLibJs() {
  return HtmlService
    .createTemplateFromFile('Lib_js')
    .getRawContent();
}
index.html
<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
    <?!= include('libLoader.js'); ?>
    <?!= include('index.js'); ?>
  </head>
  <body>
    <div id="app"></div>
  </body>
</html>
libLoader.js.html
<script>
const LibLoader = (() => {
  const DOMContentLoaded = new Promise((resolve, reject) => {
    const boot = () => {
      document.removeEventListener('DOMContentLoaded', boot);
      resolve();
    }
    document.addEventListener('DOMContentLoaded', boot);
  });
  const LibLoaded = new Promise((resolve, reject) => {
    google.script.run
      .withSuccessHandler(code => {
        const url = URL.createObjectURL(new Blob([code], {'type': 'text/javascript'}));
        import(url)
          .then(resolve)
          .catch(reject);
      })
      .withFailureHandler(reject)
      .api_loadLibJs();
  });
  return Promise.resolve()
    .then(() => DOMContentLoaded)
    .then(() => LibLoaded);
})();
</script>
index.js.html
<script type="module">;(()=>{
'use strict';

LibLoader
  .then((module) => {
    module.hello(document.getElementById('app'));
  })
  .catch(console.error);
})();</script>
Lib_js.html
//<script>
export const hello = (elm) => {
  elm.textContent = 'Hello, world!';
};
//</script>

参考

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?