@ledsun blog

無味の味は佳境に入らざればすなわち知れず

Hello script type module

いきなり既存のアプリケーションにimport mapsを導入するのはつらいことがわかりました。 もっと小さなアプリケーションから試して行きましょう。

まずは、type="module”だけをつかって、Hello worldします。

index.htmlです。

<html>
  <head>
    <script type="module">
      import { sayHello } from './hello.js';
      sayHello();
    </script>
  </head>
</html>

hello.jsです。

export function sayHello () {
  document.body.appendChild(document.createTextNode('Hello World!'))
}

ブラウザでファイルを開くと次のエラーが出ます。

Access to script at 'file:///Users/shigerunakajima/import-maps/hello.js' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, chrome-untrusted, https. hello.js:1

次のようにHTTPサーバーを起動します。

ruby -run -ehttpd . -p8000

f:id:ledsun:20211019061327p:plain
ブラウザにHello World!と表示されました。

参考

Big list of http static server one-liners · GitHub