[Vuejs]-Inlining single file components

0👍

This is possible, but you’ll lose the ability to use scoped css.

The normal, non-optimized setup will look like this:

app.html:

<html>
  <head>
    <script src="https://unpkg.com/vue"></script> 
    <script src="https://unpkg.com/http-vue-loader"></script> 
  </head>

  <body>
    <div id="my-app">
      <my-component></my-component>
    </div>

    <script type="text/javascript">
      new Vue({
        el: '#my-app',
        components: {
          'my-component': httpVueLoader('my-component.vue')
        }
      });
    </script> 
  </body>
</html>

my-component.vue:

<template>
  <div class="hello">src: Hello {{who}}</div>
</template>

<style>
  .hello {
    background-color: #ffe;
  }
</style>

<script>
  module.exports = {
    data: function() {
        return {
            who: 'world'
        }
    }
  }
</script>

The optimize-inline’d file will then need to look like this:

app.html

<html>
  <head>
    <script src="https://unpkg.com/vue"></script> 
  </head>

  <body>

    <!--============== my-component begin ==============-->
    <template id="my-component-template">
      <div class="hello">src: Hello {{who}}</div>
    </template>

    <style>
      .hello {
        background-color: #ffe;
      }
    </style>

    <script type="text/javascript">
      Vue.component('my-component', {
          template: '#my-component-template',
          data: function() {
              return {
                  who: 'world'
              }
          }
      });
    </script>
    <!--============== my-component end ==============-->

    <div id="my-app">
      <my-component></my-component>
    </div>

    <script type="text/javascript">
      new Vue({
        el: '#my-app',
        components: {
          //'my-component': httpVueLoader('my-component.vue')
        }
      });
    </script> 
  </body>
</html>

So basically the server needs to modify the content of the .vue file in the following way:

  1. rename the <template> to <template id='my-component-template'>

  2. replace module.exports = { with Vue.component('my-component',
    { template: '#my-component-template',
    and add a closing ); to the last line of the script.

Then insert this modified content into the app.html file and comment out the 'my-component': httpVueLoader('my-component.vue') line, optionally also removing the <script src="https://unpkg.com/http-vue-loader"></script> line.

Leave a comment