Encountered an issue while attempting to import a package in ES6: 'Module specifier "vue" could not be resolved'

As I dive into Vue tutorials, I find myself facing a challenge in importing Vue into a .js file and then linking this file to my index.html. The script importation in my index.html looks like this:

<script src="./js/main.js" type="module"></script>

However, when I attempt to import Vue in my main.js file:

import Vue from 'vue';

An error pops up in the browser console:

Uncaught TypeError: Failed to resolve module specifier "vue". Relative references must start with either "/", "./", or "../".

When I change my import line to:

import Vue from '../../node_modules/vue';

A different error occurs:

http://localhost:63342/vue-official-tutorial/node_modules/vue net::ERR_ABORTED 404 (Not Found)

Where am I going wrong?

Answer №1

As of June 2020

If you want to utilize ES modules directly in your Browser, follow these steps:

  1. Ensure that you are using the ESM version of your dependencies (the one with import rather than require).

    For instance, Vue ESM version can be found at:

    https://cdnjs.cloudflare.com/ajax/libs/vue/3.2.41/vue.esm-browser.prod.js

  2. Enable the experimental importmap feature in your browser.

    Update 2022: Most major browsers now support Import maps

    For older Chrome versions, this setting is located at

    chrome://flags#enable-experimental-productivity-features
    (the latest versions have moved it to
    chrome://flags#enable-experimental-web-platform-features
    )

  3. Create an importmap within your HTML file.

    At present, it only functions with inline <script> tags in Chrome. Here's an example:

<script type="importmap">
  { "imports": {
      "vue":        "https://cdnjs.cloudflare.com/ajax/libs/vue/3.2.41/vue.esm-browser.prod.js",
      "vue-router": "https://cdnjs.cloudflare.com/ajax/libs/vue-router/4.1.5/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 scripts and the imported scripts, you can now successfully import from named modules.

Import Maps Documentation


Complete example:

<html>
<body class="app">

<script type="importmap">
  { "imports": {
      "vue":               "https://cdnjs.cloudflare.com/ajax/libs/vue/3.2.41/vue.esm-browser.prod.js",
      "vue-router":        "https://cdnjs.cloudflare.com/ajax/libs/vue-router/4.1.5/vue-router.esm-browser.min.js",
      "@vue/devtools-api": "https://unpkg.com/@vue/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b8dcddceccd7d7d4cb95d9c8d1f88e968c968d">[email protected]</a>/lib/esm/index.js"
  } }
</script>

<script type="module">
  import { createRouter, createWebHistory } from 'vue-router'
  import { createApp } from 'vue'

  const app = createApp({ template: 'Hello world.' })
  const router = createRouter({
    routes: [{ path: '/:pathMatch(.*)*', component: app }],
    history: createWebHistory()
  })
  app.use(router)

  document.addEventListener('DOMContentLoaded', () => app.mount('.app'));
</script>

</body>
</html>

Answer №2

UPDATE (2020-05-10)

Discover How to Use ES6 Modules Without Webpack


When working with ES6, avoid manually inserting your main.js into index.html as this task will be taken care of by Webpack. The simplest Vue tutorial typically involves the following steps:

  1. npm install -g vue-cli
  2. vue init webpack my_project
  3. npm run dev (start developing, available result at http://localhost:8080)
  4. npm run build (result available inside the ./dist folder of your project)

Make sure to import Vue in the correct way:

import Vue from 'vue';

and not like this

import Vue from '../../node_modules/vue';

EDIT

If you prefer a beginner-friendly approach without using Webpack and single-file Vue components, start like this:

<!DOCTYPE html>
<html lang="en">

  <head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0" />
    <title>My beginners project</title>
    <link rel="stylesheet" type="text/css" href="/assets/css/styles.css" />
  </head>

  <body>
    <div id="app">
      <router-view></router-view>
    </div>
    <!-- templates for your components -->
    <template id="login">
      <div>test</div>
    </template>
    <script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="dea8abbb9eecf0ebf0efe9">[email protected]</a>/dist/vue.js"></script>
    <script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="bfc9cada92cdd0cacbdacdff8c918f918e">[email protected]</a>/dist/vue-router.js"></script>
    <!-- code for your components -->
    <script type="text/javascript" src="/app/login.js"></script>
    <!-- Vue Root component should be last -->
    <script type="text/javascript" src="/app/app.js"></script>
  </body>

</html>

Your /app/app.js file will have the following structure:

var badRoute = Vue.component('bad-route', {
    template: '<div id="bad_route"><h1>Page Not Found</h1><p>Sorry, but the page you were trying to view does not exist.</p></div>'
});
var vue_router = new VueRouter({
    base: '/app'
    , mode: 'hash'
    , routes: [{
        path: '/'
        , redirect: '/login'
    }, {
        path: '/login'
        , component: loginForm
        , name: 'LOGIN'
    }, {
        path: '*', // should be last, otherwise matches everything
        component: badRoute
        , name: 'NOT FOUND'
    }]
});
// Main application
var vue_app = new Vue({
        router: vue_router
    , })
    .$mount('#app');

The component script in your /app/login.js file will look similar to this:

var loginForm = Vue.component('login-form', {
    template: '#login', // must match the ID of the template tag
    data: function() {
        var formData = {
            username: ''
            , password: ''
        , };
        return formData;
    }
    , methods: {}
});

Answer №3

When working with Vue, using the "import vue..." syntax is only applicable when utilizing CLI and webpack.

If you are embedding Vue directly into a web page, refer to the guidelines outlined at https://v2.vuejs.org/v2/guide/installation.html#Direct-lt-script-gt-Include, where you can incorporate a line similar to this in your HTML file:

<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>

Prior to importing your own script, ensure that this line is included, so that Vue is already defined without the need for re-importing. Import your script excluding the "module" attribute. Within the script section, you can execute:

var x = new Vue({ 
  el: '#myApp',
  ... all the other stuff ...
})

This process presumes that within your HTML page, there exists:

<div id=myApp></div>

Answer №4

Migrating to TypeScript resolved the issue I was facing.

// index.html
<script type="module" src="/src/main.ts"></script>


// tsconfig.json
{
  "$schema": "https://json.schemastore.org/tsconfig",
  "extends": "@vue/tsconfig/tsconfig.json",
  "include": ["*.d.ts", "src/**/*", "src/**/*.vue"],
  "compilerOptions": {
    "baseUrl": ".",
    "moduleResolution": "node",
    "module": "ES2022",
    "strict": true,
    "target": "es2022",
    "sourceMap": true,
    "paths": {
      "@/*": ["./src/*"]
    },
    "types": ["vitest/globals"]
  },
  "references": [
    {
      "path": "./tsconfig.vite-config.json"
    }
  ]
}


// tsconfig.vite-config.json
{
  "$schema": "https://json.schemastore.org/tsconfig",
  "extends": "@vue/tsconfig/tsconfig.json",
  "include": ["vite.config.*", "vitest.config.*"],
  "compilerOptions": {
    "composite": true,
    "types": ["node"]
  }
}


// vite.config.ts
import vue from '@vitejs/plugin-vue'
import path from 'path'
import { defineConfig } from 'vite'

export default defineConfig(({ mode }) => {
  return {
    plugins: [vue()],
    resolve: {
      alias: {
        '@': path.resolve(__dirname, './src'),
      },
    },
  }
})

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error message encountered when submitting a form after receiving an AJAX response: VerifyCsrfToken Exception

I'm encountering an issue with my AJAX functionality that involves rendering a form with multiple input fields and a submit button. Here is the AJAX call: <script type="text/javascript"> $('#call_filter').click(function() { $.aja ...

Two items possess an identical worth

Whenever I make edits, both objects end up being the same. What is the solution to keep them separate? I have an object that I bind to inputs using v-model in order to update it. However, when I edit it without saving changes, the original object gets mo ...

Using an Ajax Post request to trigger a JavaScript function

Looking to execute a JavaScript function with a PHP variable, I utilized an AJAX request to send the variable named [filename] for executing the JavaScript function as follows: upload.php <script> function prepareforconvert(filenamse){ ...

Utilizing service-based global objects in Angular applications

Upon entry into my application, the GlobalApplicationController initializes several services that are utilized throughout the entire application, such as subscribing to sockets. It would be quite beneficial to have a CurrentUser object available - however, ...

How to display a three.js scene in the center of a container

I'm having trouble getting my three.js scene to display above some cards and right below my navigation bar. Currently, the scene is rendering under the cards and is not centered. Despite looking at other forum posts for help, I can't seem to figu ...

Determining the Clicked Button in React When Multiple Buttons are Present

Within my functional component, I have a table with rows that each contain an edit button. However, when I click on one edit button, changes are applied to all of them simultaneously. How can I identify which specific button was clicked and only apply chan ...

Sending an array of objects over socket io: A step-by-step guide

Recently, I've been struggling with an issue when trying to send an array of objects through socket io. This is my server-side code: var addEntity = function(ent) { entityBag.push(ent); }; var entityBag = []; addEntity(new Circle({ ...

Glitched Water Reflection in THREE.js

Creating a water scene using JavaScript. I followed the official examples to set up the scene, but the reflection seems off after loading an external GLTF model. Initially everything looks fine, but once I start moving the camera, things go awry. I suspe ...

Executing CORS request using Node.js/Express and AngularJS

I've come across multiple responses on Stack Overflow claiming that setting response headers will resolve CORS requests. However, none of the solutions have worked for me. Here is the code I have implemented: //Server.js Code var express = require(&a ...

Switch out two for loops with the find or filter method in JavaScript

In my unique approach, I am showcasing a variety of product details lists based on availability in various shops. To achieve this, I have implemented the following method. for (let i = 0; i < this.prodList.length; i++) { let setContent = false; for ...

Unable to access component data while inside a v-for loop scope

I recently started using Vue and I'm having trouble accessing my component data within a v-for loop. After implementing the code below, I encountered this error message. TypeError: Cannot read property 'whatever' of undefined at eva ...

Looking for assistance with passing values to the parent component in VUE

I am seeking assistance with my first Vue app, and as a beginner, I acknowledge that there is much I have yet to learn. Initially, I started this project by following a tutorial as part of a course, but unfortunately, the course did not cover what I am cur ...

Obtain a null value for the hidden field in ASP from a JavaScript parameter

Trying to transfer the selected parameter value from a dropdown menu to a hidden field but the hidden field always ends up empty. No errors in the JavaScript code when traced using browser debugger. What could be the issue? JavaScript $(document).ready( ...

The beforeRouteEnter callback function fails to trigger

I'm encountering an issue with my simple routes: /follower/:token/edit and /follower/new Whenever I navigate from the first route to the second one using $router.push('/follower/new'), the beforeRouteEnter hook is triggered, but the callbac ...

Updating the state within a component while specifically modifying the second item within a list

Currently in the process of constructing a battleShip game using React. Within my component, I have a state structured as follows: each coordinate is paired with a list containing two statuses - 'empty' indicating the absence of a ship ('bu ...

Transmitting text data within Google Analytics

I'm currently working on binding events for tracking with Google Analytics. When calling GA, we also have the option to send a value along with it. My goal is to send a value using a DOM selector. For example, when I use: myValue=function(){return ...

Using jquery to toggle the visibility of input fields

I'm encountering an issue with this straightforward code snippet: $("#additional-room").hide(); var numAdd = 0; $("#add-room").click(function(e) { e.preventDefault(); $("#additional-room").show(""); if (numAdd >= 3) return; numAd ...

Vue is unable to access the properties of an object

After performing a find method within an array to search for the object, I am able to retrieve the object. However, I am facing issues accessing the properties within that object. The Nuxt error message states the following: Cannot read property 'v ...

Using JQuery Ajax in Internet Explorer will only execute a single time

I've encountered an issue with my code where I have set cache to false, but in Internet Explorer it only runs once. Can someone please assist me with this problem? <script type="text/javascript" src="javascripts/jq1.7.js"></script> <sc ...

Failing to verify the presence of specific text within a dropdown menu using Selenium

Previously, I successfully implemented this code, however, the HTML/CSS for the dropdown has since changed and now I am unable to get it to function correctly. Below is the structure for the dropdown code, with specific text highlighted that I am trying t ...