Innovative approach for setting up ES6 Grunt configuration

I'm currently setting up Grunt to utilize ES6, aiming to transpile each component's JS file into its own designated folder.

Here is my current directory structure:

Components
└──footer
│   └──js
│       └──footer.jsx
└──header
│   └──js
│       └──header.jsx
└──slider
    └──js
        └──slider.jsx

My desired result is as follows:

Components
└──footer
│   └──js
│   │   └──footer.jsx
│   └──compiled
│       └──footer.js
└──header
│   └──js
│   │   └──header.jsx
│   └──compiled
│       └──header.js
└──slider
    └──js
    │   └──slider.jsx
    └──compiled
        └──slider.js

At the moment, my configuration looks like this:

babel: {
        options: {
            sourceMap: true,
            presets: ['env']
        },
        dist: {
            files: [{
                expand: true,
                cwd: "src/Components",
                src: ["**/*.jsx"],
                dest: 'compiled',
                ext: '.js',
                extDot: 'first'
            }]
        }
    }

However, it currently consolidates all compiled files into a single common folder.

What adjustments should be made in order to generate compiled JS for each individual component directory?

Answer №1

When dynamically creating the files object in Grunt, you can make use of the rename property to generate a new destination path. The logic for this requirement is handled within the rename function.

Sample Gruntfile.js:

// ...
babel: {
  options: {
    sourceMap: true,
    presets: ['env']
  },
  dist: {
    files: [{
      expand: true,
      cwd: 'src/Components',
      src: ["**/*.jsx"],
      dest: 'src/Components', // <--- Ensure this matches `cwd`
      rename: function (dest, src) {
        var destParts = dest.split('/'),
          srcParts = src.split('/');

        srcParts.splice((srcParts.length - 2), 1, 'compiled');
        return destParts.concat(srcParts).join('/');
      },
      ext: '.js',
      extDot: 'first'
    }]
  }
}
// ...

Key Points:

  1. The rename function takes two arguments, src and dest.
  2. In this function, both dest and src paths are split into arrays using split().
  3. We utilize splice() to replace the second-to-last item in the array with the new directory name, "compiled".
  4. By concatenating items from the modified srcParts array with the original dest array, we create the new destination path string.
  5. The value of the dest property must match the cwd property value in the files object.

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

Exploring the power of DOM manipulation in both jQuery UI and AngularJS UI Router

I have a query regarding the integration of jQuery UI and AngularJS UI Router. My aim is to incorporate jQuery UI themes into my application, however, when using AngularJS UI Router, I face issues with an incomplete DOM tree. Is there a way to successfull ...

Utilizing a keycode within the jQuery plugin without the need to explicitly pass it through options

I am currently working on developing a custom jQuery plugin. My goal is to be able to check the keyCode within the plugin without needing to pass it through as an option parameter. Below, you can see the code snippet that I'm using. It's a bit c ...

Incorporate a div beside a button using componentDidMount in a React component

Upon page load, I aim to position an info icon div next to a button node. However, the button node is not available when componentDidMount is triggered. I have attempted to use setTimeout, but its effectiveness varies depending on the amount of data in th ...

Retrieving external JSON data with JavaScript

I am attempting to utilize a specific service for proxy checking. They offer an uncomplicated API that delivers JSON data. My goal is to retrieve this JSON on my own server. Despite various attempts, I consistently encounter either a CORS request issue or ...

Generating PNG images with text using Node.js

I am currently working on generating a PNG file to be sent to clients through HTTP as an image/png response type. This new file will be created by combining 3 base PNG files and inserting custom text in the center of the image. Unfortunately, I have not ...

Guide on utilizing exported API endpoint in Node and Express

Seeking a deeper understanding of express and its utilization of various endpoints. Recently came across an example of an endpoint that reads in a json file, demonstrated as follows: const fs = require('fs'); const path = require('path&apos ...

Enhance the functionality of jQuery sortable by including additional details

I have a li list that I have implemented sortable functionality using jQuery. In order to ensure that the updated data is sent to the correct destination, I need to include some hidden values in the serialized data. How can I achieve this? HTML <ul i ...

What is the best way to remove all elements in jQuery?

I need to remove the selected element in my demo using jstree. I have consulted the plugin's API at http://www.jstree.com/api/#/?f=deselect_all([supress_event]), but it seems that it does not deselect the item properly. Here are the steps I have follo ...

Can you provide guidance on displaying flash messages in my template using Express.js?

app.get('/',function(req,res){ res.render('home'); // Ensure the template has access to the flash message }); app.get('/go',function(req,res){ req.flash("info", "You have gone to GO and got redirected back home!"); ...

How can I retrieve information from a Behavior Subject within an Angular service?

My goal in using BehaviouSubject was to streamline API calls and share the data with multiple components within the same route. While I've successfully achieved this, I'm facing challenges when trying to filter the received data. Here is a stack ...

Error encountered when trying to save Mongoose model - "Cannot use $inc on a non-numeric value"

Currently, I have set up 2 mongoose models in separate files. const userSchema = new mongoose.Schema({ name:{type: String, required: true}, postHistory:[{type: mongoose.Schema.Types.ObjectId, ref: "Posts"}] )}; module.exports = mongoose.model(&q ...

Tips for creating an option list on the fly

In need of help here! I have a dropdown list that needs to be dynamically populated using jQuery because the list contents are constantly changing. I initially got the code inspiration from a website, but it was built with a fixed number of items in mind. ...

Sharing data between Vue components

Recently delved into the world of Vue.js and could use some guidance. I've got two components that are not directly connected as parent and child. I attempted passing a variable between the two using "props," but it didn't work out as planned. ...

Incorporate a secondary (auxiliary) class into ReactJS

Looking to create a helper class similar to this: export default class A { constructor() { console.log(1); } test() { console.log(2); } } and utilize it within a component like so: import React, { Component } from "react"; import A from ...

Organizing an array in JavaScript that includes both version numbers and letters, with each letter representing a specific numerical value

If given an array similar to this one: input = [ "1.1", "1.c", "1.b", "1", "D", "b", "4", "2.1.2", "5.1", "3", & ...

How can you personalize a website script by deactivating it using uBlock Origin and then reintegrating it as a userscript?

Can you imagine if it were possible to address a problematic portion of a script on a website by preventing the original script from loading, copying the source code, editing it, and then re-injecting it as a userscript with Tampermonkey? I attempted this ...

How can I alleviate TypeScript compiler error TS2339 warnings?

Utilizing the TypeScript compiler has been instrumental in my coding process, as it allows me to catch potential defects at an early stage. One particular warning that the compiler flags is TS2339, which verifies if a type has a specific property defined. ...

Tips for modifying the color of a 3D object using the THREE.SceneUtils.createMultiMaterialObject function

My current project involves an object that has a unique combination of color and wireframe. I am looking to modify the base color and mesh material of this object in its final form. To achieve this, I have decided to utilize MeshBasicMaterial for the Mul ...

Downloading Several Files Simultaneously in Chrome

Since the last Chrome update, my website has encountered an issue. The code snippet below, which was designed to download multiple files, is now only opening the last file in the same tab. I have ensured that my Chrome settings still allow for multiple dow ...

KendoValidator seems to be demanding fields that do not have an actual requirement

I have a field in my form that is optional, but when I try to save the data, I encounter an issue with the validation message from Kendo. The validation should only check if it is a valid zipcode and allow it to be left blank. Additionally, the error messa ...