Error: Cannot find module ‘@vue/cli-service/generator/template/src/App.vue’ with vite

Total
1
Shares

I created a vue 3 project with vite and I wanted to add vue-router to the project, so from the terminal I wrote vue add router but after downloading everything I get the following error:

Error: Cannot find module '@vue/cli-service/generator/template/src/App.vue' from '/home/frostri/projects/onedrive_local/client/node_modules/@vue/cli-plugin-router/generator/template/src'
    at Function.resolveSync [as sync] (/usr/lib/node_modules/@vue/cli/node_modules/resolve/lib/sync.js:102:15)
    at renderFile (/usr/lib/node_modules/@vue/cli/lib/GeneratorAPI.js:515:17)
    at /usr/lib/node_modules/@vue/cli/lib/GeneratorAPI.js:300:27
    at processTicksAndRejections (node:internal/process/task_queues:96:5)
    at async Generator.resolveFiles (/usr/lib/node_modules/@vue/cli/lib/Generator.js:268:7)
    at async Generator.generate (/usr/lib/node_modules/@vue/cli/lib/Generator.js:175:5)
    at async runGenerator (/usr/lib/node_modules/@vue/cli/lib/invoke.js:111:3)
    at async invoke (/usr/lib/node_modules/@vue/cli/lib/invoke.js:92:3)

Is there anything I can do to fix it?


Solution

The vue command is from Vue CLI. Vue CLI commands (i.e., vue add router) are not intended for Vite projects despite the similarities in project structure. There currently isn’t an official Vite CLI command to automatically augment your project files to setup vue-router, so you’ll have to do it manually:

  1. Run this command from the project root to install vue-router (version 4x for Vue 3):

    npm i -S [email protected]
    # or:
    yarn add [email protected]
    
  2. Create src/router.js with the following contents:

    import { createRouter, createWebHistory } from 'vue-router'
    import HelloWorld from './components/HelloWorld.vue'
    
    export default createRouter({
      history: createWebHistory(),
      routes: [
        {
          path: '/',
          component: HelloWorld,
        }
      ]
    })
    
  3. Edit src/main.js to install the router instance:

    import { createApp } from 'vue'
    import App from './App.vue'
    import './index.css'
    import router from './router' 👈
    
    createApp(App)
      .use(router) 👈
      .mount('#app')
    
  4. Edit src/App.vue to contain:

    <template>
      <router-view />
    </template>
    
Leave a Reply

Your email address will not be published. Required fields are marked *