Home > database >  Error resolving module specifier “vue”. Relative module specifiers must start with “./”, “../” or “/
Error resolving module specifier “vue”. Relative module specifiers must start with “./”, “../” or “/

Time:02-28

I'm trying to get a basic VueJS application working using the code

<!DOCTYPE html>
<html>
<head>
    <script src="https://unpkg.com/vue@3"></script>
    <link rel="icon" href="/favicon.ico" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
</head>
<body>
    <div id="app"></div>

    <script type="module">
        import { createApp } from 'vue'
        import MyComponent from './my-component.js'

        createApp(MyComponent).mount('#app')
    </script>
</body>
</html>

But all I see is the error of 'Error resolving module specifier “vue”. Relative module specifiers must start with “./”, “../” or “/”.' when I browse to localhost:3000 on Firefox. I've been at this for hours but I can't figure out why it doesn't work when I've copied it from the VueJS page 'getting started'. I've used the commands 'npm run dev', 'npx serve' and 'npm run build' but they all return the same error in the web developer tools' console.

Any help or guidance on this would be appreciated.

CodePudding user response:

It seems that you are using the global build of Vue where all APIs are exposed under the global Vue variable (line 4 in your example).

Solution 1
Remove the import line for vue and prepend createApp with "Vue.":

//REMOVED: import { createApp } from 'vue'
import MyComponent from './my-component.js'

Vue.createApp(MyComponent).mount('#app') //NOTE that "Vue." has been added

Solution 2
Another solution would be to add an importmap block. That way, you can refer to vue as specified in the importmap and the corresponding url is resolved from there. Unfortunately, this is (at the moment) only supported by Chromium-based browsers. Luckily, a shim is available to allow use of importmap on non-Chromium browsers. See below for an example, where the shim is injected above the importmap-block. Note that the script-line for loading vue has been removed from the header-block.

<!DOCTYPE html>
<html>

<head>
  <link rel="icon" href="/favicon.ico" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
</head>

<body>
  <script async src="https://ga.jspm.io/npm:[email protected]/dist/es-module-shims.js"></script>
  <script type="importmap">
    { "imports": { "vue": "https://unpkg.com/vue@3/dist/vue.esm-browser.js" } }
  </script>
  <div id="app">{{ message }}</div>
  <script type="module">
    import { createApp } from 'vue' createApp({ data() { return { message: 'Hello Vue!' } } }).mount('#app')


  </script>
</body>

</html>
  • Related