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

Utilizing JSONLOADER in Three.js allows for efficient loading and

Currently, I am using JSONloader in three.js to load models and it works perfectly. However, I am struggling to find detailed steps or documentation on how to preload textures (which are images) in order to create an interactive feature where I can switc ...

It appears that the JavaScript array is able to modify itself autonomously

Currently, I am working on a project using P5.js where I am saving values in an array and then creating a copy of that array to manipulate. However, I have encountered an issue where manipulating the second array also changes the original one, and I cannot ...

Vue's span function is yielding the promise object

In my Vue component, I am using the function getOrderCount to fetch the number of orders from a specific URL and display it in one of the table columns. <div v-html="getOrderCount(user.orders_url)"></div> async getOrderCount(link) { ...

Effortlessly transfer files with Ajax through Box

I attempted to utilize the Box.com API for file uploads according to instructions from https://gist.github.com/seanrose/5570650. However, I encountered the following error message: `XMLHttpRequest cannot load "". No 'Access-Control-Allow-Origin&ap ...

Issue with retrieving relative time using Moment.js - fromNow()

I want to utilize moment.js to display relative time fromNow(), but I am encountering an issue where the values are being rounded and showing higher durations instead of exact completion times. For example, moment().subtract('s',110).fromNow() / ...

Setting the value of a custom component property dynamically after the component has been rendered

I'm currently developing an Angular application and have a specific requirement to work on. I am using a custom component with 3 inputs, and I want to bind this custom component tag in the HTML of my page. <my-column [setInfo]="info" [dis ...

Is there an h1 heading on this page?

Trying to enhance the accessibility of a website by properly setting up the headers. Running into issues with ensuring they are in the correct order. If there is code that could be applied across all pages to set h1 if it doesn't exist (promoting h2, ...

The AngularJS templates' use of the ternary operator

Is there a way to implement a ternary operation in AngularJS templates? I am looking for a way to apply conditionals directly in HTML attributes such as classes and styles, without having to create a separate function in the controller. Any suggestions wo ...

Exploring the contents of a JSON object

Just getting started with jquery and I'm attempting to parse a JSON object. This is my Jquery ajax call $(document).ready(function () { var resource = "v1/projects"; var url = '@Url.Action("Proxy")?resource=' + resource; ...

Guide to creating intricate designs on an HTML5 Canvas, one pixel at a time

Imagine a scenario where there is a 900x900 HTML5 Canvas element involved. In this case, there is a function named computeRow, which takes the row number as a parameter and returns an array of 900 numbers. These numbers represent colors ranging from 0 to ...

Encountering a NoEmit error with .d.ts files when using Webpack, tsconfig, and dynamic imports

I'm struggling to grasp the interaction between webpack, tsconfig, and .d.ts files in my project. This is how my project structure looks: The ScriptsApp directory includes an @types folder structured like this: Here's my tsconfig.json configur ...

Performance comparison between Javascript Object and Map/Set for key lookup

I decided to experiment with the performance of JavaScript Object, Map, and Set when it comes to accessing keys. I tested the following three code snippets on JSBEN.CH. Objects const object = {}; for (let i = 0; i < 10000; ++i) { object[`key_${i}` ...

Setting ng-click on a custom element directive in Angular 1.x: A guide

Within this code, I have assigned ng-click to a custom element directive with the expectation that clicking the rendered text would trigger an alert saying "Worked from directive!" However, the functionality does not seem to be working as intended. Althou ...

Oops! Looks like there's a problem with the helper called "if_equal" in Handlebars

I attempted to incorporate handlebars into my express node application, but it appears to be malfunctioning. const express = require('express'); const hbs = require('hbs'); const expressHbs = require('express-handlebars'); c ...

Leveraging jQuery within a webpack module shared across multiple components, located outside the webpack root directory

When working with multiple layouts that rely on shared typescript files, it is important to ensure these files are accessible across different layouts using webpack. While attempting to include jquery in my ajax.ts, I encountered the following error: ERR ...

Having Difficulty Converting JavaScript Objects/JSON into PHP Arrays

This particular inquiry has no relation to the previously mentioned identical answer/question... In JavaScript, I am dealing with a substantial list of over 1,000 items displayed in this format... var plugins = [ { name: "Roundabout - Interac ...

Showcasing the time variance using javascript/jquery

I am currently using a datepicker to select dates, with the intention of calculating the difference between the chosen dates and then displaying an alert with the calculated difference. Unfortunately, I am encountering issues with getting the code to work ...

Guide on utilizing personalized fonts with Handlebars and Puppeteer

I have a Handlebar template that I am converting to PDF using Puppeteer. My question is how can I incorporate custom fonts? Currently, I have a static folder declared in my app.js file like this: app.use(express.static(path.join(__dirname, 'assets&ap ...

Creating a Standard DIV Element (JavaScript Code)

Just a quick question here. http://jsfiddle.net/fkling/TpF24/ In this given example, I am looking to have < div>Bar 1</div> open as default... Any suggestions on achieving that? That would be all for now. Thank you so much! :D The JS script ...

Managing server JSON objects in Adobe AIR

I am facing an issue with a script that fetches objects from a remote server using an Ajax call. The server sends back objects in JSON format. However, while working on Adobe AIR, I encountered a restriction on utilizing eval() due to security concerns. As ...