DEV Community

j45t7
j45t7

Posted on

Webpack & Tailwind CSS Setup

Step by step Webpack and Tailwind CSS configuration setup.

Create package.json

npm init -y
Enter fullscreen mode Exit fullscreen mode

Create your src folder and add an empty index.js file.

Webpack Setup

Install webpack and loaders

npm install webpack webpack-cli webpack-dev-server postcss-loader css-loader
-D
Enter fullscreen mode Exit fullscreen mode

Create webpack.config.js in the root and update file.

// webpack.config.js

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  mode: 'development',
  entry: {
    bundle: path.resolve(__dirname, 'src/index.js'),
  },
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: '[name][contenthash].js',
    clean: true,
    assetModuleFilename: '[name][ext]',
  },
  module: {
    rules: [
      {
        test: /\.css$/i,
        use: ['style-loader', 'css-loader', 'postcss-loader'],
      },
    ],
  },
  devServer: {
    static: {
      directory: path.resolve(__dirname, 'dist'),
    },
    port: 3000,
    open: true,
    hot: true,
    compress: true,
    historyApiFallback: true,
  }
};
Enter fullscreen mode Exit fullscreen mode

Setup Tailwind CSS

Install Tailwind CSS

npm install -D tailwindcss postcss autoprefixer

npx tailwindcss init
Enter fullscreen mode Exit fullscreen mode

Add Tailwind to your PostCSS configuration:

// postcss.config.js

module.exports = {
  plugins: {
    tailwindcss: {},
    autoprefixer: {},
  }
}
Enter fullscreen mode Exit fullscreen mode

Configure your template paths:

// tailwind.config.js

module.exports = {
  content: ['./dist/*.html'],
  theme: {
    extend: {},
  },
  plugins: [],
}
Enter fullscreen mode Exit fullscreen mode

Add Tailwind directives to your CSS:

// styles.css

@tailwind base;
@tailwind components;
@tailwind utilities;
Enter fullscreen mode Exit fullscreen mode

Start using Tailwind in your HTML:

<!doctype html>
<html>
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link href="/dist/main.css" rel="stylesheet">
</head>
<body>
  <h1 class="text-center p-3">
    Webpack with Tailwind CSS
  </h1>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Add scripts to package.json:

"scripts": {
    "dev": "webpack serve",
    "build": "webpack"
  },
Enter fullscreen mode Exit fullscreen mode

Running Your App

To build once and create your dist/bundle.js

npm run build
Enter fullscreen mode Exit fullscreen mode

To run your webpack server

num run dev
Enter fullscreen mode Exit fullscreen mode

Now you have Webpack setup with Tailwind CSS!

To see this (and more) in action check:
GITHUB

Sources:
Tailwind CSS
Webpack

Oldest comments (2)

Collapse
 
eric23 profile image
Eric

Thanks for the detailed instructions.
Good post!

Some comments may only be visible to logged-in visitors. Sign in to view all comments.