--- lang: ja-jp breaks: true --- # Webアプリ JavaScript で `import` を使用する場合、`type="module"` が必要 2024-03-22 ```javascript= import { Utils } from './utils.js'; ・・・ ``` * `type="module"`が無いと以下のようなエラーが発生する。 * `Uncaught SyntaxError: Cannot use import statement outside a module`  ## `export` していない JavaScript を HTMLの `script` タグで呼びす場合、`import` で別のモジュールを読み込んでいる場合は、``type="module"`` が必要。 * 以下はダメ ```html= <script src="./aaaa.js"></script> ``` * 以下で動作する。 ```html= <script src="./aaaa.js" type="module"></script> ``` ## ローカル環境で実行する場合は、http~ で始まるURLで実行する必要がある。 * 以下のようなエラーが発生する。 * `index.html:1 Access to script at 'file:///C:/xxxx/aaaaa.js' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, isolated-app, chrome-extension, chrome-untrusted, https, edge.` * `Failed to load resource: net::ERR_FAILED` ### 開発中は、VSCode の `Live Preview` を使用すれば良い。  ###### tags: `JavaScript` `import` `type="module"`
×
Sign in
Email
Password
Forgot password
or
Sign in via Google
Sign in via Facebook
Sign in via X(Twitter)
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
Continue with a different method
New to HackMD?
Sign up
By signing in, you agree to our
terms of service
.