title: Using the result of a Promise in webpack.config.js
body: <p>I'm trying to access a Promise (an array of file paths) created in <strong>recursive.js</strong> (goes through my directories and sorts my stylesheets) in my <strong>webpack.config.js</strong> so I can compile all my stylesheets in a specific order.</p>
  
  <p>It seems that <strong>webpack.config.js</strong> is not able to access the result from <strong>recursive.js</strong> and it is not generating my bundle of .css/.scss files!</p>
  
  <p>I actually can't think of a way to solve this...I thought that having the <em>module.exports = { ... }</em> inside <em>.then( result => { ... } )</em> would be enough...but it I believe that module.exports tries to use result before it's even ready and it only generates <em>main.js</em></p>
  
  <p><strong>recursive.js</strong></p>
  
  <pre><code>const readdirp = require('readdirp');
  
  let files = readdirp.promise('src/lib/bs4',
      {
          entryType: 'files', fileFilter: ['*.css', '*.scss'], directoryFilter: ['!modulos', '!node_modules', '!assets']
      })
      .then(function (files) {
          return new Promise((resolve, reject) =&gt; {
              resolve(promises = files.map(files =&gt; files.path))
          })
      }).then(function (result) {
          let cssArr = []
          let scssArr = []
          result.forEach(e =&gt; {
              let temp = e.split('.')
              if (temp[temp.length - 1] === 'css') {
                  cssArr.push(e)
                  //cssArr.push(e.replace(/\\/g, '/'))
              } else {
                  scssArr.push(e)
                  //scssArr.push(e.replace(/\\/g, '/'))
              }
          })
          console.log(cssArr.concat(scssArr))
          return cssArr.concat(scssArr)
      })
  
  exports.files = files
  </code></pre>
  
  <p><strong>webpack.config.js</strong></p>
  
  <pre><code>const path = require('path');
  const MiniCssExtractPlugin = require('mini-css-extract-plugin');
  const ext = require('./recursive')
  
  
  ext.files.then((result) =&gt; {
    return new Promise((resolve, reject) =&gt; {
      resolve(promises = result.map(e =&gt; e = path.resolve(__dirname, `src/lib/bs4/${e}`)))
      // .map(e =&gt; e.replace(/\\/g, '/')))
    })
  })
    .then((result) =&gt; {
      console.log(result) // prints out the expected array of file paths!
  
      module.exports = {
        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"
          }),
        ]
      };
  
    })
  </code></pre>
  
  <p>I believe I shouldn't be using <em>module.exports</em> in my <strong>webpack.config.js</strong> file inside <strong>.then((result) => { } )</strong>.</p>
  
  <p>Are there another ways around this?</p>
  
  <p>Thanks, guys!</p>
  
  <p><strong>UPDATE</strong></p>
  
  <p>I read bit more to try and understand what FZs and Steve Holgado (Thanks a lot!) were trying to explain, and I modified my code to behave like this:</p>
  
  <pre><code>const path = require('path');
  const { CleanWebpackPlugin } = require('clean-webpack-plugin');
  const MiniCssExtractPlugin = require('mini-css-extract-plugin');
  const readdirp = require('readdirp');
  const OptimizeCssAssetsPlugin = require('optimize-css-assets-webpack-plugin');
  
  // extracts argument (path) from script command
  const args = require('minimist')(process.argv.slice(2));
  
  // development or production?
  const devMode = process.env.NODE_ENV !== "production";
  
  const configPromise = readdirp.promise('src/lib/bs4',
    {
      // if a file (stylesheets/images) is not being imported/required its extension needs to be added to the fileFilter: []
      // e.g.: removing '*.png' won't bundle images from 'src\lib\bs4\imgs'
      entryType: 'files', fileFilter: ['*.css', '*.scss', '*.png'], directoryFilter: ['!modulos', '!node_modules', '!assets']
    })
    .then(function (files) {
      return files = files.map(file =&gt; file.path);
    })
    .then(function (result) {
      return new Promise((resolve, reject) =&gt; {
        let cssArr = [];
        let scssArr = [];
        result.forEach(element =&gt; {
          let temp = element.split('.');
  
          (temp[temp.length - 1] === 'css') ? cssArr.push(element) : scssArr.push(element)
  
        })
  
        // .scss files first then .css
        result = scssArr.concat(cssArr);
        result = result.map(element =&gt; path.resolve(__dirname, `src/lib/bs4/${element}`));
  
        // Path to the first file in the queue (src/..)
        if (!args['path']) {
          console.log(' ******* Path to main stylesheet NOT added ******* ');
        } else {
          console.log(' ******* Path to main stylesheet ADDED ******* ');
          result.unshift(path.resolve(__dirname, args['path']));
        }
  
        // console.log(args['path'])
        // console.log(result)
  
        resolve({
          mode: devMode ? 'development' : 'production',
          entry: {
            // main: './src/principal.js',
            // bundle.css
            bundle: result,
          },
          output: {
            // filename: 'principal.js',
            path: path.resolve(__dirname, 'bundle-css'),
          },
          optimization: {
            minimizer: devMode ? [] : [
              new OptimizeCssAssetsPlugin({
                assetNameRegExp: /\.css$/,
              })
            ]
          },  
          module: {
            rules: [
              {
                test: /\.(sa|sc|c)ss$/,
                use: [
                  MiniCssExtractPlugin.loader, // 3. Extract css into files
                  'css-loader', // 2. Turns css into commonjs
                  'sass-loader' // 1. Turns sass into css
                ]
              },
              {
                test: /.(svg|png|jpe?g|gif)$/,
                use: [
                  {
                    loader: 'file-loader',
                    options: {
                      name: '[name].[ext]',
                      outputPath: 'images/',
                    }
                  }
                ]
              },
              {
                test: /\.(woff(2)?|ttf|eot|svg)(\?v=\d+\.\d+\.\d+)?$/,
                use: [
                  {
                    loader: 'file-loader',
                    options: {
                      name: '[name].[ext]',
                      outputPath: 'fonts/',
                      exclude: /images/, // avoid having copies of .svg fonts into 'images/'
                    }
                  }
                ]
              }
            ],
          },
          plugins: [
            new MiniCssExtractPlugin({
              filename: devMode ? '[name].[hash].css' : '[name].[hash].min.css'
            }),
            new CleanWebpackPlugin({
              cleanAfterEveryBuildPatterns: ['bundle-css'] // clean output.path directory
            })
          ]
        })
      })
    })
  
  module.exports = configPromise
  </code></pre>
  
  <p>Here are the commands I'm using to run it in case someone needs help with that too:</p>
  
  <pre><code>  "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"
    },
  </code></pre>
  
  <p>To run one of the scripts: npm run bundle-css-dev -- --path="path_to_first_file_in_queue"</p>