Can't Output Dynamic SCSS Entry points in Webpack

Viewed 204

I am using Webpack 4 and I am trying to look into a folder find all the scss files and dynamically create an entrypoint for each one found. When I look at that the function is returning it appears to be returning exactly what I need but no css files are being outputted from the function only one for the first entrypoint alternate:

Example I am using is from https://www.sitepoint.com/community/t/how-to-configure-webpack-to-output-multiple-css-files-from-sass/303659/2

I don't understand what I am doing wrong. Thanks for any help you can give.

const departmentStyles = pattern => glob
  .sync(pattern)
  .reduce((entries, filename) => {
    const [, name] = filename.match(/([^/]+)\.scss$/)
    return { ...entries, [name]: filename }
  }, {})

console.log('Departments', departmentStyles('./src/scss/alternate/departments/*.scss'))

When I log out the return value of department style I receive:
/*
Departments { alt1: './src/scss/alternate/departments/alt1.scss',
  alt2: './src/scss/alternate/departments/alt2.scss',
  alt: './src/scss/alternate/departments/alt3.scss', }
*/


module.exports = {
  entry: {
    ...departmentStyles('./scss/alternate/departments/*.scss'),
  },

  output: {
    path: path.join(__dist, 'alternate'),
    filename: 'js/[name].js',
    chunkFilename: 'js/[name].chunk.js',
  },

  plugins: [
    new MiniCssExtractPlugin({
      filename: 'css/[name].css',
      chunkFilename: 'css/[name].css'
   })
  ]
}
1 Answers

After much trial and error I have come to a solution. I have modified the way I retrieve the files first of all and then just add the object to the webpack entrypoints

const entryObject = {}
// For each file in the glob
departments.forEach(file => {
  // Will return just the file name without extension
  const name = file.match(/(?<=\/departments\/)(.*)(?=.*\.scss)/g)
  // Replace ./src with ./ so the path will resolve on build
  file = file.replace('./src/', './')
  // Build the entry object
  entryObject[name] = file
})

// The above creates an entry object of: name: 'filepath/file.css'

Then in my entry poioint I simply add the entryObject

module.exports = {
  entry: {
    tri: './js/tri.js',
    entryObject
  }

  /* Rest of the webpack stuff */
}
Related