What strategies can I employ to prevent redundancy when all my .vue files are identical?

Although I am new to Vue, there are many aspects that I find appealing. However, one thing I dislike is combining templates, scripts, and styles in the same file.

Instead, I prefer separating these concerns by using:

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

Therefore, for each component, my directory will have a structure like this:

https://i.sstatic.net/8Pa6U.png

If I follow this approach, it seems logical to me that the .vue file may become unnecessary.

There should be a way to instruct my build tools to replace x/x.vue with the above code if the file is not found.

Setting aside debates about the advantages and disadvantages of this method, how can I achieve this?

For reference, I am using Vue version 3.9.3 and willing to include any necessary npm dependencies in the project.

To clarify, while I am open to adjusting my import statements, my primary objective is to remove the need for creating and managing identical .vue files. (Ideally, the solution should use the file if it exists, in case we need to build that component differently for some reason.)

Just to emphasize, I am seeking a solution that does not alter the architecture of my components. Instead, I seek a meta-programming solution that automatically generates code that can be assumed to exist without requiring the manual creation of numerous identical implementations.

Answer №1

If you're looking for a solution similar to what you're trying to achieve, there is a package that utilizes webpack to compile separate files into a single Vue component: https://github.com/pksunkara/vue-builder-webpack-plugin

Personally, I prefer using the .vue file to set the <template> and import the necessary .js or .css/.scss files. This way, I only need three files without repeating myself too much by combining two tasks 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>

According to the official documentation, it appears that the approach mentioned above is currently the preferred method: https://v2.vuejs.org/v2/guide/single-file-components.html#What-About-Separation-of-Concerns

Answer №2

One possible solution is to organize the component by creating a folder named ProductForm. Inside this folder, include three files for template, script, and style, as well as an additional file named index.js.

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

To utilize the component, import it using:

  import ProductForm from './components/ProductForm'

This will automatically load the index.js file without explicitly mentioning it in the import statement.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unable to locate the module styled-components/native in React Native

When adding types in tsconfig.json to remove TypeScript complaints and enable navigation to a package, the code looks like this: import styled, {ThemeProvider} from 'styled-components/native'; The package needed is: @types/styled-components-re ...

Is there a way to seamlessly transfer (optional) parameters from a CloudFormation template to a CDK resource within a CfnInclude without statically defining the list of parameters?

Trying to grasp these syntax rules, unsure if it's possible. We have numerous CloudFormation templates that we want to deploy using CDK by constructing them with CfnInclude. The issue is that CfnInclude always needs an explicit parameters argument if ...

What steps do I need to follow to set up a Loading screen in Vue3 and Vite correctly?

Is there a better way to handle the loading state for an entire app instead of setting up a Loading screen with a time interval of 2 seconds using a Loading component? The Loading component has been directly integrated into the router-view of App.vue to a ...

There was an error in calling `prisma.user.findUnique()`:

Here is my code snippet for the API route: export const POST = async (req: NextRequest) => { ... try { const { email, name, password } = await req.json(); console.info(email, name, password); const existingUser = await prismadb.user.findUn ...

Error: The push was unsuccessful due to the pre-receive hook decline on the remote repository

Encountering difficulties when attempting to deploy a NodeJS app on Heroku. The error message reads: remote: Building source: remote: remote: -----> Node.js app detected remote: remote: -----> Creating runtime environment remote: remote: ...

Implement Vue JS to set default value(s) in an array

While browsing through Stack Overflow, I've noticed many questions related to Vue JS and selecting a default single value from an Array. My situation is a bit different - I need to compare each item's array groups with an array containing ALL THE ...

What is the best way to repurpose the vuex module for multiple components?

Currently, I am tackling the pagination aspect of a project that involves handling a large amount of data. My initial instinct was to store this data within Vuex. However, I ended up implementing all the logic in the Vuex store module. Now, my goal is to f ...

Ways to implement the React.FC<props> type with flexibility for children as either a React node or a function

I'm working on a sample component that has specific requirements. import React, { FC, ReactNode, useMemo } from "react"; import PropTypes from "prop-types"; type Props = { children: ((x: number) => ReactNode) | ReactNode; }; const Comp: FC< ...

Ways to Close a Modal in Ionic 5

I have a scenario where I need to open a modal, perform an asynchronous action, and then automatically dismiss the modal once the action is completed. Specifically, I want to use the fetchData function to handle the async task. @Component({ }) export cla ...

"Production mode is experiencing a shortage of PrimeNG(Angular) modules, while they are readily accessible in development

I've been diligently working on an Angular application that heavily relies on PrimeNG as the UI component framework. Initially, I had no issues deploying my app with Angular version 9 and PrimeNG version 8. However, a while ago, I decided to upgrade t ...

Transferring slot data from Parent components to Child Components

I've created a custom component called async-select based on another component, vue multiselect. Here's how: Check out the code here: https://jsfiddle.net/2x7n4rL6/4/ Although vue-multiselect provides several slots, I want to utilize them withi ...

Validate the checkbox with Vuelidate only when the specified property is set to true

I have a website login form where users may need to check a specific checkbox before logging in. Here is part of the Vue component code that handles this functionality: <script setup lang="ts"> import {ref, defineProps} from 'vue&a ...

To install bcrypt using node version 5.0.0 and npm version 3.5.1, use the command:

After updating node and npm, I encountered an error while trying to install bcrypt. The error message is as follows: sudo npm install bcrypt --save > [email protected] install /Users/XXX/node_modules/bcrypt > node-gyp rebuil ...

Next.js 13: Dealing with the "Objects are not valid as a React child" error while using async/await to retrieve data

Currently, I am working on a project using Next.js 13 and the new app directory structure. One of my tasks involves fetching data from an API. However, every time I attempt to do this with async/await, I encounter an error message stating: "Objects are not ...

Semantic-ui-react cannot be located by Docker

I am a beginner when it comes to docker and I'm looking to create a React app, specifically using TypeScript, inside a docker container. In order to do this, I need to incorporate semantic-ui-react into my project. I followed the instructions provide ...

Saving the current language (i18n) in local storage using VueJS

I'm working on a Vue app that utilizes Vue Routers and the Vue $i18n plugin. Here's how I've structured my HTML: <div class="locale-changer"> <select v-model="this.$i18n.locale" class="btn"> ...

Executing a custom node module in script commands specified in package.json file

I created a node package called my-module which functions properly. When I add this module to a larger project, I would like it to be executed through the packege.json file. Here is how it currently works: "scripts": { "myModule" : "node ./node_modul ...

Typescript: create a type similar to keyof but with a particular value type

I have an interface called MyInterface interface MyInterface { field1: boolean, field2: MyType, field3: MyType } In this interface, I want to create a new type that contains only the keys which have values of type MyType. While I know about the key ...

``Is there a way to align components with the same width side by side horizontally

I have a situation where I need to align three components, a radio button and two select fields, on the same row within a container. Currently, they are displaying on separate rows but I want them to be in three columns on a single line. I tried following ...

What is the best way to connect a globally installed node package to a project using yarn?

I'm new to using yarn and I'm having trouble connecting a globally installed package to my project. When using npm, I would typically run npm link <package-name> but this doesn't seem to work with yarn. Whenever I try running yarn link ...