😃Getting started with systemjs full (ok)

Tất cả code ở đây https://github.com/systemjs/systemjs-examples

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

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

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

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

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

<!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

<!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

C:\Users\Administrator\Desktop\practice\index.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

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");
      }
    }
  }
})

C:\Users\Administrator\Desktop\practice\index.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

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

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");
    }
  };
});

C:\Users\Administrator\Desktop\practice\index.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

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

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

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

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

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

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

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

C:\Users\Administrator\Desktop\nodejs-loader\package.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

C:\Users\Administrator\Desktop\amd-dependencies\index.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

{
  "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

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

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
        }));
      });
    }
  };
});

C:\Users\Administrator\Desktop\webpack-externals\index.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

{
  "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

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

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

C:\Users\Administrator\Desktop\amd-modules\index.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

{
  "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

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

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

C:\Users\Administrator\Desktop\react-hello-world\index.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

{
  "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

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

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

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

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

C:\Users\Administrator\Desktop\typescript-default-extension\package.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

<!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

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

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

(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

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}`)
  }
}

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

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

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

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

C:\Users\Administrator\Desktop\typescript\index.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

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

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

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

<!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

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.");
}

C:\Users\Administrator\Desktop\webpack-code-splits\index.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

{
  "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

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

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

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

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

Last updated

Navigation

Lionel

@Copyright 2023