Skip to content

Component registration via modules

Component registration via modules refers to the technique of leveraging native ES6 modules within a browser environment to define and register Vue.js components. This method enables developers to use single-file JavaScript components without requiring a build step or a transpiler like Babel, relying instead on the browser's native module support.^[600-developer__frontend__vue__vue-module.md]

Implementation Details

To utilize modules for component registration, the main entry point (e.g., app.js) must import the component definition and then register it within the Vue instance's components option.^[600-developer__frontend__vue__vue-module.md]

A core requirement for this approach is specifying <script type="module"> in the HTML host file; without this attribute, the browser will not recognize the import statements or execute the module logic correctly.^[600-developer__frontend__vue__vue-module.md]

Code Examples

HTML Structure In index.html, the Vue library and the module scripts are loaded. It is critical to assign type="module" to the scripts containing imports.

<script src="https://unpkg.com/vue"></script>
<script type="module" src="SingleFileComponent.js"></script>
<script type="module" src="app.js"></script>
^[600-developer__frontend__vue__vue-module.md]

Component Definition The component file (e.g., SingleFileComponent.js) exports a default object containing the component options, such as template and data.

export default {
  template: `
    <div>
      <h1 id="h1Msg">這個是用 script type=module 產生的 message </h1>
      <p v-text="message" ></p>
    </div>
  `,
  data() {
    return {
      message: 'brower module'
    }
  }
}
^[600-developer__frontend__vue__vue-module.md]

Application Entry In app.js, the component is imported and explicitly registered to the parent Vue instance.

import SingleFileComponent from './SingleFileComponent.js';

new Vue({
  el: '#app',
  components: {
    SingleFileComponent
  }
});
^[600-developer__frontend__vue__vue-module.md]

  • [[Vue.js]]
  • [[ES6 Modules]]
  • [[Client-side rendering]]

Sources

^[600-developer__frontend__vue__vue-module.md]