The way you can use ES modules in your Browser directly (as of June 2020) is thus:
-
Use the ESM version of your dependencies (the one that has
import
instead ofrequire
). For example, Vue ESM version is available at:https://cdnjs.cloudflare.com/ajax/libs/vue/3.0.0-beta.14/vue.esm-browser.js
-
Make your browser work with the experimental
importmap
feature. Import maps are a new web recommendation, not yet supported in mainstream browsers. https://wicg.github.io/import-maps/#import-map In Chrome this is underchrome://flags#enable-experimental-productivity-features
(latest Chrome versions moved this underchrome://flags#enable-experimental-web-platform-features
) -
Create an
importmap
in your HTML file. It only works with inline<script>
tags at the moment in Chrome. For example:
<script type="importmap">
{ "imports": {
"vue": "https://cdnjs.cloudflare.com/ajax/libs/vue/3.2.37/vue.esm-browser.min.js",
"vue-router": "https://cdnjs.cloudflare.com/ajax/libs/vue-router/4.0.16/vue-router.esm-browser.min.js"
} }
</script>
- Load your own code as an ESM module.
<script type="module" src="./main.js"></script>
- In your own scripts, and the scripts that you import – you can now successfully import from named modules.
Full example:
<html>
<body>
<script type="importmap">
{ "imports": {
"vue": "https://cdnjs.cloudflare.com/ajax/libs/vue/3.2.37/vue.esm-browser.min.js",
"vue-router": "https://cdnjs.cloudflare.com/ajax/libs/vue-router/4.0.16/vue-router.esm-browser.min.js"
} }
</script>
<script type="module">
import { createRouter, createWebHistory } from 'vue-router'
import { createApp } from 'vue'
const router = createRouter()
export default createApp({
router
})
</script>
</body>
</html>