Search code examples
vue.jsvue-componentvue3-sfc-loader

Add Vue Sfc to existing project


i have a legacy project and wanted to start using Vue.js single file components using the CDN. I did bump into some plugins such as https://github.com/FranckFreiburger/vue3-sfc-loader. Is there any solution from CDN point of view that we can:

  • generic mount to the root of the page / body ?
  • add every *.vue file from /components folder?

Then we could call those components anywhere in the existing page. I believe the plugin https://github.com/FranckFreiburger/vue3-sfc-loader only allows us to mount to a specific div#app and add a custom template (at least following the examples provided) Cheers!


Solution

  • After spending lots of time in this investigation, I went for the Vue Web Components approach

    Adding all the components to a /components folder, we will just need to have a package.json like the following

      "scripts": {
        "build": "node_modules/.bin/vue-cli-service build --target wc '/components/*.vue' --name my-app",
        "watch": "node_modules/.bin/vue-cli-service build --watch --target wc '/components/*.vue' --name my-app"
      },
      "dependencies": {
        "@vue/cli-service": "^4.5.12",
        "vue": "^2.6.12",
        "vue-template-compiler": "^2.6.12"
      }
    

    And add the following vue.config.js file in order to have only one file in the bundle

    // vue.config.js
    module.exports = {
      configureWebpack: {
        // No need for splitting
        optimization: {
          splitChunks: false
        }
      }
    }
    

    Then by adding

      <script src="https://unpkg.com/vue"></script>
      <script src="./dist/my-app.min.js"></script>
    

    to the page, we are able to use the components (see dist/demo.html to confirm the final name of the components) And for me this delivered what was needed. Hope someone can find it useful.