importing a package in ES6: “Failed to resolve module specifier “vue””

The way you can use ES modules in your Browser directly (as of June 2020) is thus:

  1. 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

  2. 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)

  3. 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>
  1. Load your own code as an ESM module.
<script type="module" src="./main.js"></script>
  1. 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>

Leave a Comment