Can the name of the Grunt task target be utilized within attributes?

I have implemented the grunt-replace task to make some content changes in the index.html file. However, I am looking for a way to avoid repeating code unnecessarily. The code snippet below is just an example of what I am trying to accomplish:

replace: {
    options: {
        patterns: [
            {
                match: /<(script.*?src=)"(?![\w/]+environment)/g,
                replacement: '<$1"//<%= config.cdn[target] %>/'
            }
        ]
    },
    a: {
        files: [
            {
                src: '<%= config.path.dist.output %>/index.html',
                dest: '<%= config.path.dist.output %>/index-a.html'
            }
        ]
    },
    b: {
        files: [
            {
                src: '<%= config.path.dist.output %>/index.html',
                dest: '<%= config.path.dist.output %>/index-b.html'
            }
        ]
    }
}

When I trigger replace:a, I expect the replacement pattern to be sourced from config.cdn['a']. Similarly, when I execute replace:b, I want the replacement pattern to come from config.cdn['b'].

Do you think this approach is feasible?

Answer №1

While it may not be the prettiest solution, this code snippet could potentially serve its purpose or provide some assistance:

executeTransformation: (function () {

    var transformations = {},
        targets = ['alpha', 'beta'],
        selectedTarget,
        index,
        count;

    for (index = 0, count = targets.length; index < count; index++) {
        selectedTarget = targets[index];

        transformations[selectedTarget] = {
            options: {
                directives: [
                    {
                        find: /<(style.*?src=)"(?![\w/]+settings)/g,
                        change: '<$1"//' + config.assets[selectedTarget] + '/'
                    }
                ]
            },
            locations: [
                {
                    source: config.paths.outputDirectory + '/home.html',
                    destination: config.paths.outputDirectory + '/home-' + selectedTarget + '.html'
                }
            ]
        }
    }

    return transformations;

}())

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

I am looking to gather user input in JavaScript and then showcase that input on the webpage. What would be the best

I am currently learning Java and I decided to challenge myself by creating a hangman game. The issue I am facing is that when the user inputs a letter, nothing happens - there is no output indicating whether the guess was correct or incorrect. I suspect th ...

Create a Rest API and implement server-side rendering concurrently using SailsJs

I am exploring the potential of utilizing the SailsJs framework for nodeJs in order to create an application. Initially, my plan was to construct a REST API in Sails and utilize AngularJs for managing the Front-End. This API would also be beneficial for o ...

The password-protected HTML blog remains hidden until the correct entry is entered into the password box, causing

After successfully creating a password redirect page where entering the correct password redirects you to another URL (psswrdtest.tumblr.com with the password as correctpsswrd, redirecting to google.com*), I attempted to improve it by making the password p ...

How to Use JavaScript Function to Rotate an Entire Webpage

For my final project in a web design class, we were tasked with creating a website that showcases our skills. I've completed the assignment and now I want to add some interesting features to make it stand out. I'm interested in using -webkit-tra ...

The new Facebook login button in my app seems to be glitchy as it fails to redirect users to the appropriate page after

I am working on a web application and have successfully integrated Facebook login from developers.facebook.com. However, I am facing an issue where after the user logs in with their Facebook credentials, they are not redirected to my application. Additiona ...

Chrome Devtool reported an error, but the majority of them are in a null file

Currently grappling with an irksome problem in Vue.js. No matter how hard I try, I just can't seem to pinpoint the error. Even when setting a debugger, all it shows is an empty file. Please take a look at the image provided. Any assistance on identify ...

I am facing difficulty importing emotion js style using dynamic variables

I recently designed a webpage that has the following appearance: https://i.stack.imgur.com/AnIXl.jpg Here is the code from my _app.tsx file: import '../styles/globals.css' import type { AppProps } from 'next/app' import { createTheme ...

HTTP 400 Error: Bad Request Callback

I'm attempting to send data using REST API through jQuery AJAX. Here's the code I am using: $.ajax({ url: 'myurl', type: 'POST', contentType: 'application/json; charset=utf-8', data: JSON.stringify(j ...

"Discover the process of incorporating two HTML files into a single HTML document with the help of

I successfully created both a bar chart and a pie chart using d3.js individually. Now, I am trying to load these charts into another HTML file using jQuery. $(document).ready(function() { console.log("ready!"); $("#piediv").load("file:///usr/local ...

React router updates the URL without affecting the actual display

I am facing an issue in my React project where the URL changes when clicking a link, but the view does not update. I have a separate route and links file, and I can't seem to figure out the problem. Here is my index.js: import React from 'react ...

I'm looking for a way to incorporate JavaScript code within an iframe tag. Specifically, I'm attempting to embed code into a Wix website using the "Embed HTML

Trying to execute the code below on a Wix website using "Embed HTML", but IFRAME is blocking scripts. Seeking help to embed custom HTML with JavaScript on platforms like Wix.com or Wordpress.com, as the embedded code is not functioning due to IFRAME restri ...

Ways to prevent a timeout when the score exceeds 1000

Could someone help me with clearing the interval and resetting the score in my code? It seems to be working fine, but when the score goes over 1000 and I hit reset, it doesn’t reset completely. I've tried placing the clearTimeout functions before e ...

Using JavaScript to sort data within specific timeframes

How can I extract data based on timestamps greater than 06? "use strict" const data = [ {timestamp: "2020-04-23 05:05", totalAvg: 2.596211180124224}, {timestamp: "2020-04-23 05:10", totalAvg: 3.22052273203436}, {timestamp: "2020-04-23 05:15", t ...

When utilizing the `express.static(__dirname)` function in Node.js with Express, the visitor may be directed to an incorrect HTML page

My website consists of a login page named login.html and an index page named index.html. I want to implement authentication so that only logged in users can access the index page. I have not set up the post method on the login HTML page. Therefore, I have ...

React: Introducing the latest router feature post-login

I'm facing an issue with the Router in React. After a successful login, I am changing the type state in Redux from 0 to 1. However, when I try to make a switch in my App file, I encounter an error. Warning: [react-router] You cannot change <Router ...

Is there a way to halt or end an interval within a function triggered by useEffect()?

I am currently working on a countdown timer script using react.js. The timer displays a 3 or 5 seconds countdown before starting, with data for these countdowns coming from another component. I am facing an issue with controlling the main countdown timer ...

"Encountered a problem while setting up the Mailgun webhook to handle both multipart and URL encoded

I have been working on creating a web hook listener for Mailgun, and I encountered an issue when I realized that Mailgun can post webhooks using either multipart or x-www-form-urlencoded content-types. Currently, my code uses Multer to handle multipart b ...

Leveraging Javascript within Objective-C

Can you help me understand how to implement this JavaScript code in Objective-C? var theFormId = $('form').filter(function() { return this.innerHTML.indexOf('forgot your password') != -1; }).attr('id'); Is there a way to int ...

The NodeJS application experiences a crash if incorrect parameters are provided to the API

Currently, I have built a CRUD API using TypeScript with Node.js, Express, and MongoDB. My goal is to ensure that the API functions correctly when the correct parameters are sent through a POST request. However, if incorrect parameters are passed, the Node ...

PHP Ajax login form to instantly authenticate without redirecting to a new page

After attempting to implement Ajax in my login form by following two different tutorials, I am still facing the issue of error messages redirecting to another page instead of displaying on the same page. I have tried to troubleshoot and compare my code wit ...