Search code examples
typescriptvue.jsnpmdrybabel-polyfill

If my .vue files are all the same, how can I avoid repetition?


I am new to Vue and there is a lot I like about it, but I do not like putting my templates, scripts, and styles all in the same file.

Instead I'd rather split the concerns by doing:

<template src="./template.html"></template>
<script lang="ts" src="./script.ts"></script>
<style lang="scss" scoped src="./style.scss"></style>

As such my directory for each component will look like

enter image description here

If I do this, however, then it seems to me that there should be a way to make the .vue file itself completely unnecessary.

There should be a way to tell tell my build tools that if it is looking for x/x.vue and this file is not found, to just fill in the gap with the code above.

Without getting into any debates as to the pros and cons of this approach, how can I do this?

For whatever it is worth, I am using vue version 3.9.3 and am prepared to add whatever npm dependencies are necessary/desirable to the project.

To be clear, while I am also open to modifying my import statements, this is not my goal. My goal is to eliminate the need for creating and maintaining the .vue files which are all expected to be identical. (The ideal solution should use the file if it does happen to exist, in case for whatever reason, we want to build that component differently.)

To be even more clear, I am not looking for a solution which will change the architecture of my components. I am looking for a meta-programming solution which will fill in code which can be implied to exist without anyone needing to write potentially hundreds of identical implementations.


Solution

  • There is a package doing something similar to what you want to achieve by leveraging webpack compiling the separate files into a single Vue component: https://github.com/pksunkara/vue-builder-webpack-plugin

    What I perosnally do is to use the .vue file for defining the <template> and also to load the needed .js or .css/.scss files. This way I leave it down to only three files and still not having too much repetition by mixing two responsibilities in one file: templating and importing

    <template>
       <p>Some code here</p>
    </template>
    
    <script src="./path_to_script.js"></script>
    <style src="./path_to_styles.css"></style>
    

    After checking the official documentation it seems the above is the currently idiomatic way of doing it: https://v2.vuejs.org/v2/guide/single-file-components.html#What-About-Separation-of-Concerns