webpack-chain icon indicating copy to clipboard operation
webpack-chain copied to clipboard

API to prepend a rule

Open sqal opened this issue 6 years ago • 2 comments

Hi. I would like to ask you for advice on how I can solve my current problem that I am struggling with. I use rules.oneOf setup in my webpack config. I won't paste the whole config because it's unnecessary, but here's a simplest example:

config.module
  .rule('')
    .oneOf('css')
      .test(/\.css$/)

Which generates

{
  module: {
    rules: [
      /* config.module.rule('') */
      {
        oneOf: [
          /* config.module.rule('').oneOf('css') */
          {
            test: /\.css$/
          }
      }
    ]
  }
}

Now. I am looking for a way to add a new rule to the beginning of an rules.oneOf array. I know I can currently do something like this

config.module
  .rule('')
  .oneOf('js')
    .before('css')
    .test(/\.m?js$/);

which will results in

{ rules: [/* js rule */, /* css rule */] 

and that's exactly what i want, but here's my problem. I don't know if css rule will be the first one in the whole set. I would like to prepend some rule to rules.oneOf array regardless of what rule is the first one in that array. if I am not mistaken, the current api does not offer solution to this problem, unless there is some clever way which I do not know about and coudn't find in the documentation? If this can't be solved using current api, is there a chance to add a new method to the api that will solve this problem? I think it would certainly be a helpful feature. Thanks for the help! :)

sqal avatar Feb 18 '19 17:02 sqal

There's indeed no API that lets you do this yet. In my blog I've created a solution for such a question: https://medium.com/xebia/theming-in-vue-single-file-components-7b88eaa0eb6e (or specifically https://gist.github.com/AlbertBrand/9697ba4cd11929f1d38204e37220115b)

AlbertBrand avatar Feb 18 '19 19:02 AlbertBrand

@AlbertBrand Thanks for sharing your workaround but I just found a simpler solution for this problem. Still it's a little bit hacky but it works :)

// get names of all oneOf rules
const oneOfsRules = Array.from(config.module.rule('').oneOfs.store.keys());

config.module
  .rule('')
  .oneOf('js')
    .before(oneOfsRules[0])
    .test(/\.m?js$/)

sqal avatar Feb 19 '19 09:02 sqal