import export - Javascript

js ファイル内で外部の js ファイルを読み込む

ES2015 から Javascript でもクラスが追加されたため外部ファイルを読み込む際に利用できます。

Javascript で使用されるモジュールシステムには、「 ES Modules 」と「 CommonJS 」があります。

「 ES Modules 」は、ブラウザと Node.js のどちらでも使用できますが、「 CommonJS 」は、Node.js でのみ使用可能です。

「 ES Modules 」を有効化するには、次のようにします。

HTML ファイル内に記述するとき

<script type="module">
  
</script>

Javascript ファイルを読み込む場合

<script type="module" src="script.js"></script>

Apache などの Web サーバーを介さず、ローカルファイルを Chrome で開いた場合、次のようなエラーが出ます。

ローカル環境に「 Apache 」などでサーバーを立てるか、一時的にブラウザの CORS(Cross-Origin-Resource-Sharing) を無効化して表示する必要があります。

ブラウザの CORS を無効にする方法は、設定の戻し忘れなどが考えられるためお勧めできません。Javascript の利用で環境構築が面倒な場合は、Node.js をインストールし簡易サーバーで起動するのが簡単です。

Access to script at 'file:///D:/js/script.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, https, chrome-untrusted.

オリジン「null」から「file:///D:/js/script.js」のスクリプトへのアクセスは CORS ポリシーによってブロックされています: クロスオリジンリクエストはプロトコルスキームでのみサポートされています: http、data、isolation-app、chrome -extension、chrome、https、chrome-untrusted。

sample

index.html

<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="UTF-8">
  <script type="module" src="script.js"></script>
  <title>sample</title>
</head>
<body>
</body>
</html>

script.js

import { hello } from './module.js';
window.onload = function(){
  hello()
}

module.js

export const hello = () => {
  console.log("hello");
}

Node.js で簡易サーバーを立てて実行する

Node.js のインストールとパッケージの ejs が必要です。

テンプレートの ejs が必要ない場合は、以下を参照してください。

ejs インストール

npm install ejs
  • example
    • index.ejs
    • module.js
    • script.js
    • server.js
    • style.css

index.ejs

<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="UTF-8">
  <!-- Javascript ファイルを読み込む場合 -->
  <script type="module" src="./script.js"></script>
  <title>sample</title>
</head>
<body>
</body>
</html>

module.js

export const hello = () => {
  console.log("hello");
}

script.js

import { hello } from './module.js';
window.onload = function(){
  hello()
}

server.js

const http = require("http");
const fs = require('fs');
const ejs = require('ejs');
const url = require('url');
const port = "5000";

const index = fs.readFileSync('./index.ejs', 'utf8');
const styleCss = fs.readFileSync('./style.css', 'utf8');
const scriptJs = fs.readFileSync('./script.js', 'utf8');
const moduleJs = fs.readFileSync('./module.js', 'utf8');

let server = http.createServer(getClient);
server.listen(port);
console.log('Server Start');

function getClient(req, res) {
  const url_parts = url.parse(req.url);
  switch(url_parts.pathname){
    case "/":
      let content = ejs.render(index);
      res.writeHead(200, { 'Content-Type': 'text/html' });
      res.write(content);
      res.end();
      break;
    case "/style.css":
      res.writeHead(200, { 'Content-Type': 'text/css' });
      res.write(styleCss);
      res.end();
      break;
    case "/script.js":
      res.writeHead(200, { 'Content-Type': 'text/javascript' });
      res.write(scriptJs);
      res.end();
      break;
    case "/module.js":
      res.writeHead(200, { 'Content-Type': 'text/javascript' });
      res.write(moduleJs);
      res.end();
      break;
  }
}

クラスを読み込む場合、module.js と script.js を次のようにします。

module.js

export class Sample{
  hello(){
    console.log("hello, World");
  }
}

script.js

import { Sample } from './module.js';
window.onload = function(){
  const sample = new Sample();
  sample.hello();
}