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 of require
). 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 under chrome://flags#enable-experimental-productivity-features
(latest Chrome versions moved this under chrome://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.0.0-beta.14/vue.esm-browser.js",
"vue-router": "https://cdnjs.cloudflare.com/ajax/libs/vue-router/4.0.0-alpha.12/vue-router.esm.js",
"vuex": "https://cdnjs.cloudflare.com/ajax/libs/vuex/4.0.0-beta.2/vuex.esm-browser.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.0.0-beta.14/vue.esm-browser.js",
"vue-router": "https://cdnjs.cloudflare.com/ajax/libs/vue-router/4.0.0-alpha.12/vue-router.esm.js",
"vuex": "https://cdnjs.cloudflare.com/ajax/libs/vuex/4.0.0-beta.2/vuex.esm-browser.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>
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…