简体   繁体   中英

Multiple Tailwind CSS classes having multiple Webpack entry points

Problem statement

So I have a React project setup with webpack and tailwind CSS.
In my webpack config I have multiple entry point in order to generate different CSS and JS for each entry point.
The problem arises when I use the tailwind classes in my React components.
Let's suppose if I use a tailwind class bg-red-600 only in Component1(or entry point 1).
So after building the files through webpack the bg-red-600 will be present in all the entry point's generated CSS files(keep in mind I have just used this class in first entry point component only).
What it should be doing is only have bg-red-600 class in first component CSS file instead it is preset in all the CSS files even though I have not used it in any other place other than first component.

Hope I was able to made my point.

Thanks.

Webpack's entry points:

entry: {
    app1: path.resolve(
        __dirname,
        'src/Component1'
    ),
    app2: path.resolve(
        __dirname,
        'src/Component2'
    ),

},

Here is my solution:

  1. /config folder with custom tailwind-xxx.config file for each entry js

eg. /config/tailwind-ConfirmButton.config.js :

module.exports = {
  content: [
    './src/common/ConfirmButton/ConfirmButton.jsx',
  ],
  // plugins: [require('@tailwindcss/forms')],
}


  1. webpack.config.js
const postcssOpts = { postcssOptions: env => {
    // here is the point
    const component = env._module.context.slice(env._module.context.lastIndexOf('/') + 1)

    return { 
      plugins: [
        ['tailwindcss', {
          config: `./config/tailwind-${component}.config.js`,
        }],
        autoprefixer
      ] 
    }
  } 
}

...

entry: {
  confirm: path.resolve(__dirname, './src/widgets/confirmButton.js'),
},
target: ['web', 'es5'], // <=== can be omitted as default is 'web'
output: {
  filename: '[name]/tag.js',
  path: path.resolve(__dirname, 'dist/exp'),
  publicPath: './',
},

...

{
  test: /\.css$/,
  use: [
    { loader: 'style-loader' },
    { loader: 'css-loader' },
    {
      loader: 'postcss-loader',
      options: postcssOpts,
    },
  ],
},
  1. entry widget js eg. /src/widgets/customButton.js :
...

render(
  <ConfirmButton
    expId={expId}
    content={content}
    confirmBtn={confirmBtn}
    cancelBtn={cancelBtn}
    field={field}
  />,
  container
)
  1. finally run weppack --mode=production

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM