Leveraging the outcome of a Promise within webpack's configuration file

Currently, I am facing a challenge in accessing a Promise which is essentially an array of file paths created within recursive.js. This script navigates through my directories and organizes my stylesheets. The main issue arises when trying to utilize this information in my webpack.config.js to compile all stylesheets in a specific order.

Despite my efforts, it seems like webpack.config.js is unable to retrieve the desired data from recursive.js, resulting in failure to generate the bundle of .css/.scss files!

I have tried various approaches to resolve this matter but none seem to be effective. Initially, I assumed that placing module.exports = { ... } inside .then( result => { ... } ) would suffice. However, it appears that module.exports attempts to utilize the result before it's fully prepared, ultimately leading to the generation of only main.js

The code snippet below illustrates the implementation within recursive.js:

[Insert provided recursive.js code here]

Within webpack.config.js, I have made some adjustments as well:

[Insert modified webpack.config.js code here]

It seems evident that using module.exports within webpack.config.js under .then((result) => { } ) might not be the correct approach.

Are there any alternative methods to tackle this issue?

Thank you for your assistance!

UPDATE

After exploring more insights to comprehend the guidance from FZs and Steve Holgado (Appreciate it!), I have refined my code structure as follows:

[Insert updated code snippet showcasing changes implemented]

Below are the commands utilized to execute the code effectively:

"scripts": {
    "bundle-css-dev": "cross-env NODE_ENV=development webpack --config ./bundle-css.config.js --progress --colors",
    "bundle-css-prod": "cross-env NODE_ENV=production webpack --config ./bundle-css.config.js --progress --colors"
  }

To run a specific script, use: npm run bundle-css-dev -- --path="path_to_first_file_in_queue"

Answer №1

To extract a function from webpack.config.js and return a promise is possible.

Webpack will pause for the resolution of the promise:

const path = require('path');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const ext = require('./recursive')

module.exports = () => {
  return ext.files
    .then((result) => {
      return new Promise((resolve, reject) => {
        resolve(promises = result.map(e => e = path.resolve(__dirname, `src/lib/bs4/${e}`)))
        // .map(e => e.replace(/\\/g, '/')))
      })
    })
    .then((result) => {
      console.log(result) // displays the expected array of file paths!

      return {
        entry: {
          bundle: result,
          main: [
            path.resolve(__dirname, 'src/principal')
          ]
        },
        output: {
          filename: '[name].js',
          path: path.resolve(__dirname, 'dist'),
        },
        module: {
          rules: [
            {
              test: /\.(sa|sc|c)ss$/,
              use: [
                MiniCssExtractPlugin.loader,
                'css-loader',
                'sass-loader'
              ]
            },
          ],
        },
        plugins: [
          new MiniCssExtractPlugin({
            filename: "[name].css"
          }),
        ]
      }
    })
}

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

Incorporating Stripe into your Next.js 13 application: A step-by-step guide

Struggling to incorporate Stripe into my Next.js 13 app for a pre-built checkout form. So far, all attempts have fallen short. Seeking assistance from anyone who has conquered this integration successfully. Any tips or guidance would be highly valued. Pl ...

Ways to efficiently group and aggregate data in JavaScript, inspired by LINQ techniques

I'm feeling overwhelmed by this. Could you lend a hand? Consider the following .NET classes: Teacher: public class Teacher { public int Id { get; set; } public string FirstName { get; set; } public string LastName { get; set; } publ ...

Altering the language code on LinkedIn

As a beginner in programming, I successfully added the linkedin share button to my test webpage. Now, I am hoping to make the button change language based on the user's language selection on the webpage. Linkedin uses a five character language code ( ...

What is the best way to arrange images in a 3 by 3 grid, beginning at position 0, using JavaScript to control navigation through button clicks?

When I click on button 1, it starts at image 1 because the counter is set to 0. Clicking on button 2 takes me to image 4 with a counter value of 3, while clicking on button 3 leads to image 7 with a counter value of 6. The process should also work in reve ...

Designing an interactive header interface using React and Material UI

My header.jsx file contains the following code: // Default Import Statements var Login = require(login.jsx) const HeaderComponent = React.createClass({ getInitialState () { return { loggedIn: false, }; }, render() { return ( ...

Is there a way to retrieve the current map center coordinates using the getCenter function in @react-google-maps/api?

I am currently working with the GoogleMap component provided by @react-google-maps/api, but I am struggling to figure out how to obtain the latitude and longitude coordinates of the map's center after it has been moved. After some research, I came ac ...

The outcome of a function within the $.ajax method is transformed into a string

Trying to pass an array of IDs using the $.ajax data variable is proving to be a challenge. The array is generated by a function, and I've noticed that if I define this function outside of the $.ajax call, it works fine. However, when I place the same ...

When attempting to access the length of a JSON array, it results in undefined

I recently received a JSON encoded array from an AJAX call that looks like this: {"country":{"0":"United States of America","United States of America":{"states":{"0":"Alaska","Alaska":{"cities":["Adak","Akiachak","Akiak","Akutan","Alakanuk"]}}}}} Below ...

Is it possible to check dynamically if a string contains multiple substring matches?

Currently, I am in the process of developing a search suggest feature that will provide the best match based on certain criteria. Below is the code snippet along with my explanatory comments. /* string = {"Canna Terra PLUS 50 Litres", "Canna Vega ...

Generating HTML content from XML data with the help of JavaScript

Challenge: Attempting to display one question and its four corresponding answers at a time from an XML file. JavaScript code: var xmlDoc, quest, ans, i, n; xmlDoc = loadXMLDoc("questions.xml"); quest = xmlDoc.getElementsByTagName('main'); do ...

Issue encountered while using Typescript with mocha: Unable to utilize import statement outside a module

Exploring the world of unit testing with mocha and trying to create a basic test. Project Structure node_modules package.json package-lock.json testA.ts testA.spec.ts tsconfig.json tsconfig.json { "compilerOptions": { "target&qu ...

Navigating with React-router can sometimes cause confusion when trying

I'm having trouble with my outlet not working in react-router-dom. Everything was fine with my components until I added the Outlet, and now my navigation component isn't showing even though other components are rendering. import Home from ". ...

I encountered an error while trying to add a document to Firestore using the 'add' method in Vue.js. Can someone provide guidance on how to

Whenever the function is triggered (on click), I aim to include a new document. Although it functions with .set(), my goal is for a new document to be created each time the form is submitted. The current error code I am encountering is: I initially suspe ...

Utilizing JavaScript Files Instead of NPM as a Library for Open Layers: A Step-by-Step Guide

I've been attempting to get Open Layers to function in my Eclipse web development environment, but I've encountered some challenges along the way. The setup instructions provided on the Open Layers website focus mainly on using npm. Nevertheless, ...

Ways to address observables in Angular in a manner similar to deferred objects

Transitioning from AngularJS to Angular has posed a challenge for me, especially when it comes to moving from promises to observables. Below is an example of my code in AngularJS: var deferred = $q.defer(), frame = document.createElement('newFrame ...

How can you establish an environmental variable in node.js and subsequently utilize it in the terminal?

Is there a way to dynamically set an environmental variable within a Node.js file execution? I am looking for something like this: process.env['VARIABLE'] = 'value'; Currently, I am running the JS file in terminal using a module whe ...

What is the method for obtaining a unique id that changes dynamically?

Having trouble accessing the dynamically generated ID in jQuery? It seems to work fine in JavaScript but not in jQuery. Here's an example of the issue: My jQuery code: var img = $("#MAP"+current_img_height); $("#map").css({'height': img.h ...

Unveil the Expressjs middleware within the API Client

I am currently developing a Nodejs API Client with the following simple form: //client.js function Client (appId, token) { if (!(this instanceof Client)) { return new Client(appId, token); } this._appId = appId; this._token = tok ...

Transform an array of strings into a JSON object or array

Is there a way to transform a JavaScript string array into a JSON string? var arr = "{'id': '10', 'name': 'test1'},{'id': '11', 'name': 'test2'}"; This would allow for easy a ...

Is it possible to run a local file on a localhost server in Sublime Text 3 with the help of the SideBar

I am attempting to host my index.html file on a localhost server in order to utilize an angular routing directive. Despite following the steps, I am encountering issues. //sidebarenchancements.json { "file:///C:/Users/Jdog/Desktop/projects/Calibre/soci ...