# Getting started with systemjs full (ok)

**Hai cách load module ngoài trình duyệt dễ nhất :)**

```javascript
export const helloWorld = () => {
  console.log('Hello world 123!');
};
```

C:\Users\Administrator\Desktop\amd-dependencies\helloWorld.js

```javascript
import { helloWorld } from './helloWorld.js';
helloWorld();
```

C:\Users\Administrator\Desktop\amd-dependencies\index.js

```html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <script type="module" src="index.js"></script>
</head>
<body>
</body>
</html>
```

C:\Users\Administrator\Desktop\amd-dependencies\test.html

**Hoặc**

```html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <script type="module">
    // Wrap code in a function to prevent a top-level await.
    (async () => {
      // The next line raises a SyntaxError in intermediate browsers.
      const { helloWorld } = await import('./helloWorld.js');
      // The next line in only executed if the browser supports
      // dynamic imports. It is never executed in intermediate browsers.
      helloWorld();
    })();
  </script>
</head>
<body>
</body>
</html>
```

C:\Users\Administrator\Desktop\amd-dependencies\test.html

Đọc ở bài bên dưới <https://javascriptuse.gitbook.io/advanced/doc-them-bai-nay-mo-dun-ecmascript-va-kha-nang-tuong-thich-trinh-duyet-ok>

## systemjs-features

### [basic-import-map](https://systemjs.github.io/systemjs-examples/systemjs-features/basic-import-map/)&#x20;

<figure><img src="/files/6y0x94egss84Jbxgxljb" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/XRd8Dv2L9oAEFQUOHEjF" alt=""><figcaption></figcaption></figure>

C:\Users\Administrator\Desktop\practice\index.html

```html
<!DOCTYPE html>
<html lang="en-US">
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>Basic SystemJS Example</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <script type="systemjs-importmap">
    {
      "imports": {
        "mercury": "./mercury.js",
        "single-spa": "//cdn.jsdelivr.net/npm/single-spa/lib/system/single-spa.min.js"
      }
    }
  </script>
  <!-- load a locally hosted module -->
  <script type="systemjs-module" src="import:mercury"></script>
  <!-- load a module from CDN -->
  <script type="systemjs-module" src="import:single-spa"></script>
  <!-- load SystemJS itself from CDN -->
  <script src="//cdn.jsdelivr.net/npm/systemjs/dist/system.js"></script>
</head>
<body>
</body>
</html>
```

C:\Users\Administrator\Desktop\practice\mercury.js

```javascript
System.register([], function (_export, _context) {
  return {
    execute: function () {
      document.body.appendChild(Object.assign(document.createElement('p'), { textContent: "Mercury is the planet nearest to the sun" }))
      /* The doAlert function is exported and can be used like this:
         System.import('mercury').then(mercuryModule => {
           mercuryModule.doAlert();
         })
       */
      _export('doAlert', doAlert);
      function doAlert() {
        alert("I hear it's quite warm on Mercury");
      }
    }
  }
})
```

### [dynamic-import](https://systemjs.github.io/systemjs-examples/systemjs-features/dynamic-import/)

<figure><img src="/files/ikk4Km3eifeAWOi6y5ry" alt=""><figcaption></figcaption></figure>

C:\Users\Administrator\Desktop\practice\index.html

```html
<!DOCTYPE html>
<html lang="en-US">
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>SystemJS Dynamic Import Example</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <script type="systemjs-importmap">
    {
      "imports": {
        "neptune": "./neptune.js"
      }
    }
  </script>
  <!-- load a locally hosted module -->
  <script type="systemjs-module" src="import:neptune"></script>
  <!-- load SystemJS itself from CDN -->
  <script src="//cdn.jsdelivr.net/npm/systemjs/dist/system.js"></script>
</head>
<body>
</body>
</html>
```

C:\Users\Administrator\Desktop\practice\neptune.js

```javascript
System.register([], function (_export, _context) {
  return {
    execute: function() {
      document.body.appendChild(Object.assign(document.createElement('p'), {
        textContent: 'Neptune is a planet that revolves around the Sun'
      }));
      // Dynamic import within a module calculates a url relative to the current module
      _context.import('./triton.js').then(function (triton) {
        console.log("Triton was discovered on", triton.discoveryDate);
      });
    }
  };
});
```

C:\Users\Administrator\Desktop\practice\triton.js

```javascript
System.register([], function (_export, _context) {
  return {
    execute: function() {
      document.body.appendChild(Object.assign(document.createElement('p'), {
        textContent: 'Triton is a moon that revolves around Neptune.'
      }));
      _export("discoveryDate", "Oct. 10, 1846");
    }
  };
});
```

### [import-map-scopes](https://systemjs.github.io/systemjs-examples/systemjs-features/import-map-scopes/)

<figure><img src="/files/gEInifHwWhppW3MwvdRi" alt=""><figcaption></figcaption></figure>

C:\Users\Administrator\Desktop\practice\index.html

```html
<!DOCTYPE html>
<html lang="en-US">
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>Import Map Scopes SystemJS Example</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <script type="systemjs-importmap">
    {
      "imports": {
        "main": "./main/main.js",
        "dep": "./dep-v1.js"
      },
      "scopes": {
        "./main/": {
          "dep": "./dep-v2.js"
        }
      }
    }
  </script>
  <!-- load SystemJS itself from CDN -->
  <script src="//cdn.jsdelivr.net/npm/systemjs/dist/system.js"></script>
  <script>
    System.import('main').then(main => {
      console.log('main module was loaded', main);
    });
    System.import('dep').then(dep => {
      console.log('dep, loaded as top level module', dep);
    });
    // prepareImport simply waits for all import maps to be processed
    // You must do so before calling System.resolve()
    System.prepareImport().then(function () {
      System.import('dep', System.resolve('main')).then(dep => {
        console.log('dep, loaded relative to main module', dep);
      });
    });
  </script>
</head>
<body>
  <h1>Check browser console for details</h1>
</body>
</html>
```

C:\Users\Administrator\Desktop\practice\main\main.js

```javascript
System.register(['dep'], function (_export) {
  let dep;
  return {
    setters: [
      function (ns) {
        dep = ns;
      }
    ],
    execute: function () {
      console.log('main is executing. dep version is', dep.version);
      _export('default', 'main');
    }
  }
})
```

C:\Users\Administrator\Desktop\practice\dep-v1.js

```javascript
System.register([], function (_export) {
  return {
    execute: function () {
      _export('version', 'v1');
    }
  };
});
```

C:\Users\Administrator\Desktop\practice\dep-v2.js

```javascript
System.register([], function (_export) {
  return {
    execute: function () {
      _export('version', 'v2');
    }
  };
});
```

### [nodejs-loader](https://systemjs.github.io/systemjs-examples/systemjs-features/nodejs-loader/)

<figure><img src="/files/y5JWf7imwuUhspgPxKNY" alt=""><figcaption></figcaption></figure>

C:\Users\Administrator\Desktop\nodejs-loader\main.js

```javascript
const url = require('url');
const { System, applyImportMap, setBaseUrl } = require('systemjs');
// Setting base URL is optional - the default is to use process.cwd()
// so the code here is redundant
const basePath = url.pathToFileURL(process.cwd()).href;
setBaseUrl(System, basePath);
applyImportMap(System, {
  imports: {
    "antarctica": "./antarctica.js"
  }
});
System.import('antarctica').then(ns => {
  console.log('antarctica module', ns);
});
```

C:\Users\Administrator\Desktop\nodejs-loader\antarctica.js

```javascript
System.register([], (_export) => ({
  execute() {
    _export('default', "Antarctica is the southern continent");
  }
}));
```

C:\Users\Administrator\Desktop\nodejs-loader\package.json

```json
{
  "name": "nodejs-loader",
  "version": "1.0.0",
  "description": "This example shows SystemJS running in the browser.",
  "main": "main.js",
  "scripts": {
    "start": "node main.js"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "systemjs": "latest"
  }
}

```

## loading-dependencies

### [amd-dependencies](https://systemjs.github.io/systemjs-examples/loading-dependencies/amd-dependencies/)

<figure><img src="/files/FZFNdm0JqWhzKE82FB6G" alt=""><figcaption></figcaption></figure>

C:\Users\Administrator\Desktop\amd-dependencies\index.html

```html
<!DOCTYPE html>
<html lang="en-US">
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>AMD Dependencies - SystemJS Example</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <script type="systemjs-importmap">
    {
      "imports": {
        "titan": "./lib/titan.js",
        "rxjs": "//cdn.jsdelivr.net/npm/rxjs/bundles/rxjs.umd.min.js"
      }
    }
  </script>
  <script src="//cdn.jsdelivr.net/npm/systemjs/dist/system.js"></script>
  <script src="//cdn.jsdelivr.net/npm/systemjs/dist/extras/amd.js"></script>
  <!-- The named-exports extra is important to avoid having to rxjs.default.of() (and similar for all other rxjs functions) -->
  <script src="//cdn.jsdelivr.net/npm/systemjs/dist/extras/named-exports.js"></script>
</head>
<body>
  <div id="react-container"></div>
  <script>
    System.import('titan')
  </script>
</body>
</html>
```

C:\Users\Administrator\Desktop\amd-dependencies\package.json

```json
{
  "name": "amd-dependencies",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "build": "babel src --out-dir lib --plugins=@babel/plugin-transform-modules-systemjs"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@babel/cli": "^7.7.5",
    "@babel/core": "^7.7.5",
    "@babel/plugin-transform-modules-systemjs": "^7.7.4"
  }
}

```

C:\Users\Administrator\Desktop\amd-dependencies\src\titan.js

```javascript
import { of, from } from 'rxjs';

of("Saturn").subscribe(
  planet => {
    document.body.appendChild(Object.assign(
      document.createElement('p'),
      {textContent: `Titan is a moon orbiting ${planet}.`}
    ))
  }
)

const titanFacts = [
  "Titan is 50% more massive than Earth's moon, and 80% more massive.",
  "Titan is the only moon known to have a dense atmosphere, and the only known body in space, other than Earth, where clear evidence of stable bodies of surface liquid has been found."
];

from(titanFacts).subscribe(
  fact => {
    document.body.appendChild(Object.assign(
      document.createElement('p'),
      {textContent: fact}
    ))
  }
);
```

C:\Users\Administrator\Desktop\amd-dependencies\lib\titan.js

```javascript
System.register(["rxjs"], function (_export, _context) {
  "use strict";

  var of, from, titanFacts;
  return {
    setters: [function (_rxjs) {
      of = _rxjs.of;
      from = _rxjs.from;
    }],
    execute: function () {
      of("Saturn").subscribe(planet => {
        document.body.appendChild(Object.assign(document.createElement('p'), {
          textContent: `Titan is a moon orbiting ${planet}.`
        }));
      });
      titanFacts = ["Titan is 50% more massive than Earth's moon, and 80% more massive.", "Titan is the only moon known to have a dense atmosphere, and the only known body in space, other than Earth, where clear evidence of stable bodies of surface liquid has been found."];
      from(titanFacts).subscribe(fact => {
        document.body.appendChild(Object.assign(document.createElement('p'), {
          textContent: fact
        }));
      });
    }
  };
});
```

### [webpack-externals](https://systemjs.github.io/systemjs-examples/loading-dependencies/webpack-externals/)

<figure><img src="/files/kqcnCbKNqO9omnrpJYB7" alt=""><figcaption></figcaption></figure>

C:\Users\Administrator\Desktop\webpack-externals\index.html

```html
<!DOCTYPE html>
<html lang="en-US">
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>Webpack Externals - SystemJS Example</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <script type="systemjs-importmap">
    {
      "imports": {
        "vue": "//cdn.jsdelivr.net/npm/vue@2.7.14",
        "jupiter": "./dist/bundle.js"
      }
    }
  </script>
  <script src="//cdn.jsdelivr.net/npm/systemjs/dist/system.js"></script>
  <script src="//cdn.jsdelivr.net/npm/systemjs/dist/extras/amd.js"></script>
</head>
<body>
  <div id="vue-container"></div>
  <script>
    System.import('jupiter')
  </script>
</body>
</html>
```

C:\Users\Administrator\Desktop\webpack-externals\package.json

```json
{
  "name": "webpack-externals",
  "scripts": {
    "build": "webpack"
  },
  "license": "MIT",
  "devDependencies": {
    "clean-webpack-plugin": "^3.0.0",
    "webpack": "^4.41.2",
    "webpack-cli": "^3.3.10"
  },
  "dependencies": {}
}

```

C:\Users\Administrator\Desktop\webpack-externals\webpack.config.js

```javascript
const path = require('path');
const { CleanWebpackPlugin } = require('clean-webpack-plugin')
module.exports = {
  entry: path.resolve(__dirname, 'src/entry.js'),
  mode: 'development',
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'dist'),
    libraryTarget: 'system',
  },
  devtool: 'sourcemap',
  plugins: [new CleanWebpackPlugin()],
  // Webpack externals will be shared across bundles and come from the import map and systemjs
  externals: ['vue', 'vue-router'],
};
```

C:\Users\Administrator\Desktop\webpack-externals\src\entry.js

```javascript
import Vue from 'vue';
console.log('Vue', Vue);
const App = Vue.default.extend({
  template: '<p>Jupiter has {{numMoons}} moons',
  data: () => ({
    numMoons: 79,
  })
});
new App().$mount('#vue-container');
```

## loading-code

### [amd-modules](https://systemjs.github.io/systemjs-examples/loading-code/amd-modules/)

<figure><img src="/files/GZvOS6Px62nh9KxerCyR" alt=""><figcaption></figcaption></figure>

C:\Users\Administrator\Desktop\amd-modules\index.html

```html
<!DOCTYPE html>
<html lang="en-US">
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>AMD Modules - SystemJS Example</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <script type="systemjs-importmap">
    {
      "imports": {
        "saturn": "./lib/saturn.js"
      }
    }
  </script>
  <script src="//cdn.jsdelivr.net/npm/systemjs/dist/system.js"></script>
  <script src="//cdn.jsdelivr.net/npm/systemjs/dist/extras/amd.js"></script>
  <script>
    System.import('saturn');
  </script>
</head>
<body>
</body>
</html>
```

C:\Users\Administrator\Desktop\amd-modules\package.json

```json
{
  "name": "amd-modules",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "build": "babel src --out-dir lib --plugins=@babel/plugin-transform-modules-amd"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@babel/cli": "^7.7.5",
    "@babel/core": "^7.7.5",
    "@babel/plugin-transform-modules-amd": "^7.7.5"
  }
}

```

C:\Users\Administrator\Desktop\amd-modules\src\saturn.js

```javascript
import * as neptune from './neptune.js'
document.body.appendChild(Object.assign(
  document.createElement('p'),
  {
    textContent: "Saturn is 1,433,449,370 km from the Sun, on average."
  }
));
neptune.showDistanceFromSun();
```

C:\Users\Administrator\Desktop\amd-modules\src\neptune.js

```javascript
export function showDistanceFromSun() {
  document.body.appendChild(Object.assign(
    document.createElement('p'),
    {
      textContent: "Neptune is 4,503,443,661 km from the Sun, on average."
    }
  ));
}
```

### [react-hello-world](https://systemjs.github.io/systemjs-examples/loading-code/react-hello-world/)

<figure><img src="/files/YZ0xvZYOptDgcNkS4yvn" alt=""><figcaption></figcaption></figure>

C:\Users\Administrator\Desktop\react-hello-world\index.html

```html
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>SystemJS AMD Modules from CDN Example</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <script type="systemjs-importmap">
    {
      "imports": {
        "react": "//cdn.jsdelivr.net/npm/react/umd/react.production.min.js",
        "react-dom": "//cdn.jsdelivr.net/npm/react-dom/umd/react-dom.production.min.js"
      }
    }
  </script>
  <script src="//cdn.jsdelivr.net/npm/systemjs/dist/system.min.js"></script>
</head>
<body>
  <div id="react-root"></div>
  <script type="systemjs-module" src="./dist/react-hello-world.js"></script>
</body>
</html>
```

C:\Users\Administrator\Desktop\react-hello-world\package.json

```json
{
  "name": "react-hello-world",
  "version": "1.0.0",
  "scripts": {
    "build": "babel src --out-dir dist --source-maps"
  },
  "license": "MIT",
  "devDependencies": {
    "@babel/cli": "^7.6.0",
    "@babel/core": "^7.6.2",
    "@babel/plugin-transform-modules-systemjs": "^7.5.0",
    "@babel/preset-react": "^7.0.0"
  },
  "dependencies": {}
}

```

C:\Users\Administrator\Desktop\react-hello-world\src\react-hello-world.js

```javascript
import React from 'react';
import ReactDOM from 'react-dom';

ReactDOM.render(<button>A button created by React</button>, document.getElementById('react-root'));
```

C:\Users\Administrator\Desktop\react-hello-world\\.babelrc

```jsonc
{
  "presets": [
    "@babel/preset-react",
  ],
  "plugins": [
    "@babel/plugin-transform-modules-systemjs"
  ],
}
```

### [ypescript-default-extension](https://systemjs.github.io/systemjs-examples/loading-code/typescript-default-extension/)

C:\Users\Administrator\Desktop\typescript-default-extension\tsconfig.json

```jsonc
{
  "compilerOptions": {
    "outDir": "dist",
    "sourceMap": true,
    "target": "es2015",
    "module": "system",
    "lib": ["es2015", "dom"]
  }
}

```

C:\Users\Administrator\Desktop\typescript-default-extension\package.json

```json
{
  "name": "typescript-default-extension-example",
  "scripts": {
    "build": "tsc"
  },
  "devDependencies": {
    "@types/lodash": "^4.14.149",
    "@types/systemjs": "^6.1.0",
    "typescript": "^3.8.3"
  }
}

```

C:\Users\Administrator\Desktop\typescript-default-extension\index.html

```html
<!DOCTYPE html>
<html lang="en-US">
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>Basic Typescript SystemJS Example</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <script type="systemjs-importmap">
    {
      "imports": {
        "lodash": "//cdn.jsdelivr.net/npm/lodash@4.17.15/lodash.min.js"
      }
    }
  </script>
  <script src="//cdn.jsdelivr.net/npm/systemjs/dist/system.js"></script>
  <script src="./dist/systemjs-hooks/resolve.js"></script>
  <script>System.import("./dist/typescript-example")</script>
</head>
<body>
</body>
</html>
```

C:\Users\Administrator\Desktop\typescript-default-extension\src\typescript-example.ts

```typescript
import _ from 'lodash';
import { isPlanet } from './helpers/planet-helpers';
import { RealPlanets, NotRealPlanets } from './planets';
document.body.appendChild(Object.assign(document.createElement('p'), {
  textContent: 'Pluto is no longer considered a planet. (Check you console for more information).'
}))
/* In a browser console, you can use the isPlanet function with the following code:
  System.import('planet-checker').then(planetChecker => {
    const isPlanet = planetChecker.isPlanet('thing');
  })
*/
// Planet operations
isPlanet(RealPlanets.Earth);
isPlanet(NotRealPlanets.Pluto);
// Just a demonstration that lodash is available, since the systemjs-importmap in index.html
// specifies where to fetch lodash
console.log('Real Planets');
_.each(RealPlanets, planet => console.log(planet));

```

C:\Users\Administrator\Desktop\typescript-default-extension\src\planets.ts

```typescript
export type InterstellarObjects = RealPlanets | NotRealPlanets
export enum RealPlanets {
  Mercury = 'Mercury',
  Venus = 'Venus',
  Earth = 'Earth',
  Mars = 'Mars',
  Jupiter = 'Jupiter',
  Saturn = 'Saturn',
  Uranus = 'Uranus',
  Neptune = 'Neptune',
}
export enum NotRealPlanets {
  Pluto = 'Pluto',
}

```

C:\Users\Administrator\Desktop\typescript-default-extension\src\systemjs-hooks\resolve.ts

```typescript
(function () {
  const endsWithFileExtension = /\/?\.[a-zA-Z]{2,}$/;
  const originalResolve = System.constructor.prototype.resolve;
  System.constructor.prototype.resolve = function () {
    // apply original resolve to make sure importmaps are resolved first
    const url = originalResolve.apply(this, arguments);
    // append .js file extension if url is missing a file extension
    return endsWithFileExtension.test(url) ? url : url + ".js";
  };
})();
```

C:\Users\Administrator\Desktop\typescript-default-extension\src\helpers\planet-helpers.ts

```typescript
import { InterstellarObjects, NotRealPlanets, RealPlanets } from '../planets'
export function isPlanet(planetName: InterstellarObjects) {
  if (RealPlanets[planetName]) {
    console.log(`${planetName} is a planet!`)
    return true
  } else if (NotRealPlanets[planetName]) {
    console.log(`${planetName} is not a planet!`)
    return false
  } else {
    throw Error(`Unknown planetName ${planetName}`)
  }
}

```

### [typescript](https://systemjs.github.io/systemjs-examples/loading-code/typescript/)

<figure><img src="/files/tJrMWLC6eKwpDAy318Nc" alt=""><figcaption></figcaption></figure>

C:\Users\Administrator\Desktop\typescript\package.json

```json
{
  "name": "typescript-example",
  "scripts": {
    "build": "tsc"
  },
  "devDependencies": {
    "typescript": "^3.6.4"
  }
}

```

C:\Users\Administrator\Desktop\typescript\tsconfig.json

```jsonc
{
  "compilerOptions": {
    "outDir": "dist",
    "sourceMap": true,
    "target": "es2015",
    "module": "system",
    "lib": ["es2015", "dom"]
  }
}
```

C:\Users\Administrator\Desktop\typescript\index.html

```html
<!DOCTYPE html>
<html lang="en-US">
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>Basic Webpack SystemJS Example</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <script type="systemjs-importmap">
    {
      "imports": {
        "planet-checker": "./dist/typescript-example.js"
      }
    }
  </script>
  <script type="systemjs-module" src="import:planet-checker"></script>
  <script src="//cdn.jsdelivr.net/npm/systemjs/dist/system.js"></script>
</head>
<body>
</body>
</html>
```

C:\Users\Administrator\Desktop\typescript\src\typescript-example.ts

```typescript
document.body.appendChild(Object.assign(document.createElement('p'), {
  textContent: 'Pluto is no longer considered a planet.'
}))
/* In a browser console, you can use the isPlanet function with the following code:
System.import('planet-checker').then(planetChecker => {
  const isPlanet = planetChecker.isPlanet('thing');
})
*/
export function isPlanet(planetName: InterstellarObjects) {
  if (RealPlanets[planetName]) {
    console.log(`${planetName} is a planet!`)
    return true
  } else if (NotRealPlanets[planetName]) {
    console.log(`${planetName} is not a planet!`)
    return false
  } else {
    throw Error(`Unknown planetName ${planetName}`)
  }
}
type InterstellarObjects = RealPlanets | NotRealPlanets
enum RealPlanets {
  Mercury = 'Mercury',
  Venus = 'Venus',
  Earth = 'Earth',
  Mars = 'Mars',
  Jupiter = 'Jupiter',
  Saturn = 'Saturn',
  Uranus = 'Uranus',
  Neptune = 'Neptune',
}
enum NotRealPlanets {
  Pluto = 'Pluto',
}
isPlanet(RealPlanets.Earth)
isPlanet(NotRealPlanets.Pluto)
```

## optimized-builds

### [basic-webpack](https://systemjs.github.io/systemjs-examples/optimized-builds/basic-webpack/)

<figure><img src="/files/duc1zme4rw9ldObc7Khd" alt=""><figcaption></figcaption></figure>

C:\Users\Administrator\Desktop\basic-webpack\webpack.config.js

```javascript
const path = require('path');
const { CleanWebpackPlugin } = require('clean-webpack-plugin')
module.exports = {
  entry: path.resolve(__dirname, 'src/entry.js'),
  mode: 'development',
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'dist'),
    libraryTarget: 'system',
  },
  devtool: 'sourcemap',
  plugins: [new CleanWebpackPlugin()],
};
```

C:\Users\Administrator\Desktop\basic-webpack\index.html

```html
<!DOCTYPE html>
<html lang="en-US">
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>Basic Webpack SystemJS Example</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <script type="systemjs-importmap">
    {
      "imports": {
        "earth": "./dist/bundle.js"
      }
    }
  </script>
  <script type="systemjs-module" src="import:earth"></script>
  <script src="//cdn.jsdelivr.net/npm/systemjs/dist/system.js"></script>
</head>
<body>
</body>
</html>
```

C:\Users\Administrator\Desktop\basic-webpack\src\entry.js

```javascript
document.body.appendChild(Object.assign(document.createElement('p'), {
  textContent: "Earth is a planet that revolves around the sun"
}))
/* To use the doAlert function, run the following in the browser console:
System.import('earth').then(earthModule => {
  earthModule.doAlert();
})
*/
export function doAlert() {
  alert("Earth is home to billions of humans and other life forms.");
}
```

### [webpack-code-splits](https://systemjs.github.io/systemjs-examples/optimized-builds/webpack-code-splits/)

<figure><img src="/files/X7lFZcWJj65ig5mRU96T" alt=""><figcaption></figcaption></figure>

C:\Users\Administrator\Desktop\webpack-code-splits\index.html

```html
<!DOCTYPE html>
<html lang="en-US">
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>SystemJS Example - Webpack Code Splits</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <script type="systemjs-importmap">
    {
      "imports": {
        "mars": "./dist/bundle.js"
      }
    }
  </script>
  <script type="systemjs-module" src="import:mars"></script>
  <script src="//cdn.jsdelivr.net/npm/systemjs/dist/system.js"></script>
</head>
<body>
</body>
</html>
```

C:\Users\Administrator\Desktop\webpack-code-splits\package.json

```json
{
  "name": "webpack-code-splits",
  "scripts": {
    "build": "webpack"
  },
  "license": "MIT",
  "devDependencies": {
    "clean-webpack-plugin": "^3.0.0",
    "webpack": "^4.41.2",
    "webpack-cli": "^3.3.10"
  },
  "dependencies": {
    "systemjs-webpack-interop": "^1.1.0"
  }
}

```

C:\Users\Administrator\Desktop\webpack-code-splits\webpack.config.js

```javascript
const path = require('path');
const { CleanWebpackPlugin } = require('clean-webpack-plugin')
module.exports = {
  entry: path.resolve(__dirname, 'src/entry.js'),
  mode: 'development',
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'dist'),
    libraryTarget: 'system',
  },
  devtool: 'sourcemap',
  plugins: [new CleanWebpackPlugin()],
};
```

C:\Users\Administrator\Desktop\webpack-code-splits\src\entry.js

```javascript
import './set-public-path'
document.body.appendChild(Object.assign(document.createElement('div'), { textContent: "Are there aliens on Mars?" }))
document.body.appendChild(Object.assign(document.createElement('button'), { textContent: "Click to find out", onclick: findAliens }))
/* This function can be called with the following code:
System.import('mars').then(marsModule => {
  marsModule.findAlens();
})
*/
export function findAliens() {
  import('./sentient-aliens.js')
}
```

C:\Users\Administrator\Desktop\webpack-code-splits\src\set-public-path.js

```javascript
import { setPublicPath } from 'systemjs-webpack-interop'
// equivalent to __webpack_public_path__ = System.resolve('mars').slice(0, System.resolve('mars').lastIndexOf('/') + 1)
setPublicPath('mars')
```

C:\Users\Administrator\Desktop\webpack-code-splits\src\sentient-aliens.js

```javascript
document.body.appendChild(Object.assign(document.createElement('pre'), {
  textContent: `
       .-""""-.        .-""""-.
      /        \\      /        \\
     /_        _\\    /_        _\\
    // \\      / \\\\  // \\      / \\\\
    |\\__\\    /__/|  |\\__\\    /__/|
     \\    ||    /    \\    ||    /
      \\        /      \\        /
       \\  __  /        \\  __  / 
        '.__.'          '.__.'
         |  |            |  |
         |  |            |  |
  `,
}))
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://javascriptuse.gitbook.io/advanced/getting-started-with-systemjs-full-ok.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
