What is the best way to instruct Vite to exclude specific files within a directory from the build process?

After initializing a fresh Vue application with the command npm create vue, I implemented a functionality where the app fetches a configuration at runtime and extracts a component name from it. These dynamic components reside in a directory called "pluggables."

.
└── src
    ├── App.vue
    └── pluggables
        ├── ThisFoo.vue
        └── ThatBar.vue

Essentially, the App.vue file performs the following actions:

<script setup lang="ts">
import { onMounted, shallowRef, defineAsyncComponent } from "vue";

const pluggableComponent = shallowRef();

onMounted(() => {
  // fetching configuration
  const componentName = "ThisFoo"; // extracted from configuration

  pluggableComponent.value = defineAsyncComponent(() => import(`./pluggables/${componentName}.vue`));
});
</script>

<template>
  <div>Showing Pluggable below:</div>
  <component :is="pluggableComponent" />
</template>

During build time, I am aware of the components required at runtime and those that can be considered as "dead code" based on the configuration. Is there a method to instruct Vite to exclude unnecessary components from the build?

For instance, excluding the entire pluggables directory while including specific components from it:

vite build --exclude ./src/pluggables/** --include ./src/pluggables/ThisFoo.vue

Alternatively, I could devise a custom Vite build function to execute during the CI/CD process and provide an array of component names to process.

Answer №1

If you want to exclude certain files from the build process, you can designate them as external files using the external configuration provided by Rollup

// custom.config.js
import { defineConfig } from "custom";
import react from "@custom/plugin-react";
import * as path from "path";
import { fileURLToPath } from "node:url";

const excludeTheseFiles = ["src/components/File1.js", "src/components/File2.js"];

const filepathsToExclude = excludeTheseFiles.map((src) => {
  return fileURLToPath(new URL(src, import.meta.url));
});

// https://customjs.dev/config/
export default defineConfig({
  plugins: [react()],
  resolve: {
    alias: {
      "@": path.resolve(__dirname, "./src"),
    },
  },

  build: {
    manifest: true,
    rollupOptions: {
      external: [
        ...filepathsToExclude
      ],
    },
  },
});

Answer №2

I found success by simply adding { "exclude": [] } to the tsconfig.json file.
This approach worked well for me. (Although I am unsure if it is the correct method.) (I am utilizing React with Typescript, not Vue.)

Answer №3

After looking at a response from Duannx, I devised a solution to exclude all but the desired components in a directory

import { readdirSync } from 'node:fs'
import { join } from 'node:path'
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'

function getPluggablesToExclude(): string[] {
  const rawPluggablesToInclude = process.env.PLUGGABLES; // !! set this env variable in the CI pipeline !!

  if (!rawPluggablesToInclude) { // if missing, exclude nothing
    return [];
  }

  const pluggablesToInclude = rawPluggablesToInclude.split(',').map(component => `${component}.vue`);

  const pluggablesDirectoryPath = join(__dirname, 'src', 'pluggables');
  const filesInPluggablesDirectory = readdirSync(pluggablesDirectoryPath);

  const filesToExclude = filesInPluggablesDirectory.filter(file => !pluggablesToInclude.includes(file));

  return filesToExclude.map(file => join(pluggablesDirectoryPath, file));
}

export default defineConfig({
  plugins: [vue()],
  build: {
    rollupOptions: {
      external: [
        ...getPluggablesToExclude()
      ],
    },
  },
})

To exclude unwanted components during the build process, I just need to configure the env variable in my CI pipeline. Neglecting this step will result in every component being included in the build.

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

Create HTML content from a file retrieved from the server

I have been working on a dynamic website project, diving into web development from scratch despite having coding experience in general. As I navigate Angular CLI and Bootstrap, I've come across a fundamental question: Do modern websites house all thei ...

Using jQuery to display items from GitHub API in a custom unordered list format

Attempting to access data from the GitHub API using jQuery (AJAX) and display it on a static webpage. Here are the HTML and JS code snippets: $(document).ready(function(){ $.ajax({ url: 'https://api.github.com/re ...

Troubleshooting Node.js and MySQL: Queries failing to return expected results

I'm currently using Node.js to connect with MySQL. One issue I'm facing is that a SELECT query is not returning the desired result. However, when I use an INSERT query, it works perfectly! To tackle the problem with the SELECT query, I decided ...

Use a swipe gesture to move through the slideshow on a touchscreen device

I am currently working on a slideshow that allows users to navigate through images by clicking either the next or previous buttons. When a user clicks on one of these buttons, the next or previous image is loaded into the img src, as shown below. In addit ...

Leverage the power of jQuery to fetch data from a PHP script connected to a MySQL database

It might be a bit confusing, so let me clarify. I'm working on a form where users input a ticket and it gets assigned to a technician based on the service they offer. I have 3 text fields: username, email, and description of the problem. The next fie ...

When an input is disabled in "react-hook-form", it may return undefined

Within my React application, there exists a form containing various input fields. I have enclosed these fields using FormProvider imported from react-hook-form and utilized register within each field. import { useForm, FormProvider, useFormContext } from & ...

What is the process of using observables in Angular to retrieve a number or variable?

While working on an angular service that calls an API and processes a large amount of data, I encountered an issue. I was trying to count the occurrences of each type in the data and send back that count along with the data itself. However, I found that wh ...

Using AngularJS translation capabilities with UI Router

I am working on an AngularJS application that utilizes the AngularJS Translate library from . The setup includes UI router to maintain the existing URL structure of the website, which has been indexed by Google with various language versions such as www.do ...

Is it necessary to have n_ if I've already set up lodash?

After some research, I came across a recommendation to install lodash. However, upon visiting the lodash website, they suggest that for NodeJS, n_ should be installed instead. Are both necessary? Is one more comprehensive than the other? Do I even need eit ...

Exploring the connection between Vue's $refs and kebab-case

In the earlier version of Vue, like vue 1, you could achieve this: <app v-ref:test-app></app> and then refer to it using: vm.$refs.testApp; However, in Vue 2, the syntax for the ref has been updated to: <app ref="test-app"></app ...

Tips for running a function at regular intervals in NodeJS

I've experimented with the setInterval() method before. While it seemed ideal, the problem I encountered was that it didn't start the first call immediately; instead, it waited for X seconds before producing the desired value. Is there an alterna ...

Is it possible to create an array of strings in Vue Bootstrap by separating them with commas from a

How can I extract both number and alpha strings from a text area in Vue Bootstrap and then save them into an array? The strings are separated by commas when entered. Additionally, it would be great if these strings could appear as 'pills' or tags ...

Reloading the React/Laravel application causes the app to crash and display a blank page

My current setup involves a react application running on the Laravel 5.4 framework. The problem I'm facing is that whenever I refresh a page with a URL structure like {url}/{slug}, it causes issues within the application. Within my App.js file, here ...

Using jQuery to load HTML response into entire page

When working with my ajax code, I receive a html response. Is there a way to entirely replace the current page with this html response? So far, I have only come across window.location.href, which simply redirects to the url response. Here is a snippet of ...

What is the process for syncing ng-model with external data sources?

Here is a question that I have pondered: Let's consider the HTML code snippet below: <div id="container" ng-controller="Controller"> <my-tag ng-model="values"></my-tag> </div> Now, take a look at the controller defined a ...

React / Express / MySQL - Best Practices for Managing MySQL Transactions

I'm currently working on a project that involves developing a React front-end with an Express back-end API that utilizes MySql. One of the challenges I am facing is determining where to handle MySql transactions in my project structure. The folder l ...

Can someone explain why v-for is unable to display the computed value?

When selecting a city and area, the data should be filtered accordingly. However, I am facing an issue where the selected value does not appear. I have tried various solutions and searched for similar code, but I have yet to find a resolution. Below is a ...

Adjust the size of the wrapper/mask as the browser is resized

Is there a way to adjust the size of my wrapper and mask when the browser is resized? Currently, the mask stops once it's loaded, causing the content to be cut off when scrolling. You can view an example on this site. $(document).ready(function() { ...

It appears that Vivus JS is having difficulty animating specific <path> elements

I've been experimenting with the Vivus JS library, which is fantastic for animating paths such as drawing an image. However, I'm facing an issue where my SVG icon should animate to a 100% line-width, but it's not working as expected. Interes ...

Executing actions on events in a Basic jQuery sliderLearn how to handle events and execute

I utilized the slider from the bjqs plugin at after reviewing the documentation, I noticed it only offers options and lacks events/functions. I am referring to events/functions like onSlideChange and onSlideDisplay. While other plugins such as bxslid ...