Move the Vite build files to a different directory post-build

I currently have multiple Vue projects alongside a Wordpress project. One of the Vue projects is built with Webpack, while the other one is built with Vite.

The folder structure is as follows:

project
  |
  |__vue-project-webpack
  |   |
  |   |__dist
  |
  |__vue-project-vite
  |   |
  |   |__dist
  |
  |__wordpress project
      |
      |__target

The files in the Vue projects' `dist` folders are used in the `wordpress/target` folder.

However, I am facing an issue with copying build files from the Vite project's `dist` folder to the `target` folder of the Wordpress project. Currently, this task is being done manually.

In the webpack project, the fsTest library handles this:

configureWebpack: (config) => {
    if (process.env.NODE_ENV === 'production') {
      config.output.filename = 'js/webpack-[name].js';
      config.output.chunkFilename = 'js/webpack-[name].js';
    }
    config.plugins = [
      ...config.plugins,
      {
        apply: (compiler) => {
          compiler.hooks.afterEmit.tap('AfterEmitPlugin', () => {
            const webpackAssets = [
              {
                source: `${PATHS.dist}/js/webpack-app.js`,
                dest: `${PATHS.wpAssets}/js/webpack-app.js`,
              },
            ];
            const options = { overwrite: true };
            webpackAssets.forEach(item => {
              fsTest.copy(item.source, item.dest, options, err => {
                if (err) return console.error(err);
                console.log('Copy build success!');
              });
            });
          });
        },
      },
    ];
  },

I am struggling to find a similar solution in Vite, as all file copy plugins run before the build rather than after. Is there a way to execute them post-build completion?

Furthermore, the files generated have hashed names like index-d8c14379.css. Is there a method to rename them to something like vite-app-styles.css?

Answer №1

Regarding your initial inquiry, my suggestion is to incorporate a copy command post a successful build. To automate this process, consider adding it to the build scripts section of package.json

"scripts": {
    "build": "vite build && cp dist/* -r '../wp/target'",
  },

As for your second question, I may need further clarification. Could you provide more details on that?

Updated response to the second question

Initially, the hash present in each file serves a useful purpose by keeping your website current. I recommend giving it some more thought before deciding to remove it.

However, if you do wish to remove the hash, a solution can be found here. This involves tweaking the vite configuration slightly

export default defineConfig({
  plugins: [react(), eslint()], // please disregard this comment
  build: {
    rollupOptions: {
      output: {
        entryFileNames: `assets/[name].js`,
        chunkFileNames: `assets/[name].js`,
        assetFileNames: `assets/[name].[ext]`,
      },
    },
  },
});

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

Creating an HTML structure that limits each li to only contain three div elements can be achieved using React and Underscore.js

To achieve this specific layout, I am looking to utilize only underscore.js functions. Below is the array that I have: var xyz = [{ 'name': 'test' },{ 'name': 'test1' },{ 'name': &ap ...

Exploring the possibilities of integrating JavaScript with Flash technology

Currently, there is a simple Flash project in development that connects to an RTMP server and streams video and audio from a webcam. The project allows users to create a stream with a specific name. This project also features an input for entering a strea ...

Issues with hover functionality in React Material Design Icons have been identified

I'm facing an issue with the mdi-react icons where the hovering behavior is inconsistent. It seems to work sometimes and other times it doesn't. import MagnifyPlusOutline from "mdi-react/MagnifyPlusOutlineIcon"; import MagnifyMinusOutli ...

My element is not being animated by Elementbyclass

Without Using JQUERY The animation I'm trying to create isn't functioning properly. I attempted to utilize document.getElementsByClassName, but it's not working as expected. There are no errors, but the element is not animating correctly. ...

"Explore the versatility of React Day Picker with customizable months and weekdays_long

I have implemented the following packages: "react": "^18.2.0", "react-day-picker": "^8.1.0", and I am attempting to translate the months and days into French. However, despite passing the translated arrays to my < ...

Is it possible to execute the .push() method on an array a specific number of times without using a for loop?

Currently, I am tackling the "Move Zeroes" Leetcode challenge. The task requires moving all zeroes to the end of the array without altering the sequence of non-zero elements. My strategy involves iterating through the array, splicing out each zero encounte ...

Retrieve data in the parent component as new data is added in the child component in Vue, without relying on a watcher

Is there another way in Vue to automatically display updated data without using a watcher? Similar to React's useEffect that triggers a render when the data changes. I'm looking for an alternative that doesn't require dedicated resources to ...

In my React JS class component, I am looking to have the image display switch each time the button is clicked

How can I change the image when clicking a button in a class component? I am familiar with function components, but unsure how to achieve this. class CoffeeImages extends React.Component{ constructor(props){ super(props) ...

Locating the save directory with fileSystem API

I've been working on saving a file using the fileSystem API. It appears that the code below is functional. However, I am unable to locate where the saved file is stored. If it's on MacOS, shouldn't it be in this directory? /Users/USERNAM ...

What could be causing the delay in $q.all(promises).then() not waiting for the promises to complete?

Currently, I am tasked with utilizing AngularJS 1.5.5. My task involves making calls to multiple Rest-Services and handling the results simultaneously. $scope.callWebservices = function(){ let promises = { first: callFirstWebservice(), ...

What is the best way to modify a node_module file consisting of only a few exported variables, which is heavily utilized in the entire module? (with demonstration)

I have integrated a node module with the file structure displayed below. Inside the file node_core_ctx.js, I found this code snippet: const EventEmitter = require('events'); let sessions = new Map(); let publishers = new Map(); let idlePlayers ...

Converting SVG with an external PNG file embedded into a standalone PNG format using Node

Does anyone know of a node package that can convert an svg file to a png, including external images embedded within the svg code like this? <?xml version="1.0" encoding="utf-8"?> <svg viewBox="0 0 120 120" height="120" width="120" xmlns="h ...

React is throwing an error message stating that setCount is not a valid function

Getting an error saying setCount is not a function. I am new to this, please help. import React, { memo, useState } from "react"; export const Container = memo(function Container() { const { count, setCount } = useState(0); return ( ...

Update the content inside the extension by modifying its innerHTML

Just starting out with JavaScript, I'm attempting to create a basic extension that can generate a random number. document.getElementById("submit").onclick = function() { a = document.getElementById("in1").value; b = document.getElementById("in2 ...

Is it possible to have the soft keyboard automatically appear when the page loads?

On an HTML5 website, I have an input element and I want the soft keyboard to automatically appear and focus on that input element. I attempted to use the 'autofocus' attribute on the 'input' element, but this only focused on the element ...

Interactive Form directly linked to SQLite3 database

Looking for assistance with converting a modal from static, fake data to dynamic data from an SQLite3 database. The goal is to display a table of existing data and allow users to add new rows by clicking a +New button. However, when trying to incorporate ...

Displaying a variable in a live HTML user interface

I have successfully created a Python program that captures data from an Arduino Potentiometer and shows it on the Python console. Now, I am working on enhancing the output by displaying it in a local HTML file. I am seeking guidance on how to incorporate t ...

What is the best way to organize angularjs controllers and directives within one another?

When I structure my controllers like this: <body ng-app="app" ng-controller="ctrl"> <div ng-controller="app-get"> <app-get></app-get> </div> <div ng-controller="app-post"> <app-post">& ...

Discover the steps for dynamically integrating ionRangeSliders into your project

Recently, I integrated ionRangeSlider to display values to users using sliders. To set up a slider, we need to define an input tag like this: <input type="text" id="range_26" /> Then, we have to use jQuery to reference the input tag's ID in or ...

Customizing Drop Down Button in React Material-UI with Conditions

Trying to figure out how to dynamically populate the second MUI dropdown based on the selection from the first dropdown. Currently, I have both dropdown lists hardcoded. const [queryType, setqueryType] = React.useState(''); const [subCategory, se ...