Search code examples
vue.jswebpackcdnvuejs3vue-loader

Vue compiler can't resolve 'vue'


Version 3.0.5

Reproduction link https://github.com/clark-cui/vue3-problem

Steps to reproduce yarn

npm run dev

What is expected? devServer work successfully.

What is actually happening? Module not found: Error: Can't resolve 'vue' in 'F:\workspace_github\vue3-problem'

I didn't use vue-cli or vite to build this reposity.

so I use "vue-loader": "^16.1.2" and "@vue/compiler-sfc": "^3.0.0" to resolve '.vue'.

If i use cdn to import vue.Then it occur error like this.

If i use npm to import vue.This problem is solved.

This hadn't happen in vue2.I guess it's vue-compiler 's falut.

I want to use vue with cdn.How to solve this?


Solution

  • In order to work with vue from CDN you have to configure externals to tell webpack uses the external one. Additionally you have to refine a few things as following to make it work properly:

    // webpack.config.js
    module.exports = {
      // ...
      externals: {
         // tell `webpack` to resolve `vue` from root (window)
         vue: "Vue",
      },
      devServer: {
         // ...
         // might have to turn of this option since it throws error
         // not sure where it comes from though :(
         hot: false,
      }
    }
    

    Refine the template a bit:

    
    // index.html
    <!DOCTYPE html>
    <html lang="en">
    
    <head>
      <!-- Move the script to here to ensure load `Vue` before your script -->
      <script src="https://cdn.bootcdn.net/ajax/libs/vue/3.0.0/vue.global.prod.js"></script>
      <title>Vue demo</title>
    </head>
    
    <body>
      <noscript>
        <strong>error</strong>
      </noscript>
      <div id="app"></div>
    </body>
    
    </html>