• Stars
    star
    102
  • Rank 334,520 (Top 7 %)
  • Language
    JavaScript
  • Created about 8 years ago
  • Updated over 6 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Tutorial on adding PostCSS to `create-react-app` CLI

Install the create-react-app CLI

npm install -g create-react-app

Create the app with create-react-app CLI

# create with create-react-app PROJECT_NAME
create-react-app postcss-example
# change into the postcss-example directory
cd postcss-example
# eject the app to expose dependancies and configuration files
npm run eject

Hook up CSS modules

// change: webpack.config.dev.js
{
   test: /\.css$/,
   include: srcPath,
   loader: 'style!css!postcss'
},
// to:
{
  test: /\.css$/,
  include: srcPath,
  loader: 'style!css?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]&camelCase!postcss'
},

Breaking it down:

style is loading the style-loader

!css is loading the style-loader. The ! is how loaders can be chained together

?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]&camelCase

There is a lot to digest here. Let's break it down piece by piece.

modules turns on css modules

importLoaders=1 The query parameter importLoaders allow to configure which loaders should be applied to @imported resources.

localIdentName is the localization format of the CSS class. We are using the format [name]__[local]___[hash:base64:5] which is the FileName__LocalClassName__12345

&camelCase sets the option to convert dash cased class names like my-class-name to be myClassName in your javascript

Install Your PostCSS dependancies

I recommend using:

npm i autoprefixer postcss-initial postcss-import postcss-mixins postcss-nested postcss-simple-vars postcss-math postcss-color-function --save-dev

Now setup a postCSS config file:

Inside /config folder create a postcss.config.js file

var postCSSConfig = [
/* autoprefix for different browser vendors */
require('autoprefixer'),
/* reset inherited rules */
require('postcss-initial')({
  reset: 'inherited' // reset only inherited rules
}),
/* enable css @imports like Sass/Less */
require('postcss-import'),
/* enable mixins like Sass/Less */
require('postcss-mixins')({
  mixins: require('../src/mixins')
}),
/* enable nested css selectors like Sass/Less */
require('postcss-nested'),
/* require global variables */
require('postcss-simple-vars')({
  variables: function variables() {
    return require('../src/variables')
  },
  unknown: function unknown(node, name, result) {
    node.warn(result, 'Unknown variable ' + name)
  }
}),
/* PostCSS plugin for making calculations with math.js  */
require('postcss-math'),
/* transform W3C CSS color function to more compatible CSS. */
require('postcss-color-function')
]

// Export the PostCSS Config for usage in webpack
module.exports = postCSSConfig;

Also create variables.js and mixins.js in your config folder

// src/mixins.js
var globalMixins = {
  /* noSelect is a static mixin  */
  noSelect: {
    '-webkit-touch-callout': 'none',
    '-webkit-user-select': 'none',
    '-khtml-user-select': 'none',
    '-moz-user-select': 'none',
    '-ms-user-select': 'none',
    'user-select': 'none'
  },
  /* OpenSans is a dynamic mixin  */
  OpenSans: function (obj, value) {
    return {
      'font-family': 'Open Sans, sans-serif',
      'font-style': 'normal',
      'font-size': value,
      'font-weight': 200,
      '-webkit-font-smoothing': 'antialiased',
      '-moz-osx-font-smoothing': 'grayscale'
    }
  }
}
module.exports = globalMixins
// src/variables.js
var globalVariable = {
  primary: 'blue'
}
module.exports = globalVariable

Now import the PostCSS config file into your webpack.config

// in /config/webpack.config.dev.js
/* import postcss config array */
var postCSSConfig = require('./postcss.config')

// in the webpack config add the postCSS Config Array.
module.exports = {
  entry: [...],
  output: {...},
  resolve: { extensions: [...] },
  resolveLoader: {...},
  module: { loaders: [...] },
  // Add postcss to webpack config object
  postcss: function() {
    return postCSSConfig;
  },
  plugins: [...]
}

Usage:

Using ClassNames

import React, { Component } from 'react';
import logo from './logo.svg';
import styles from './App.css';

class App extends Component {
  render() {
    return (
      <div className={styles.app}>
        <div className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <h2>Welcome to React</h2>
        </div>
        <p className="App-intro">
          To get started, edit <code>src/App.js</code> and save to reload.
        </p>
      </div>
    );
  }
}

Variables + Mixins

You can now use the global mixins and variables!

Now in /src/App.css

/* in /src/App.css */
.intro {
  color: $primary; /* variable usage */
  @mixin noSelect; /* mixin usage */
  @mixin OpenSans 30px; /* mixin with value usage */
}

Profit

More Repositories

1

analytics

Lightweight analytics abstraction layer for tracking page views, custom events, & identifying visitors
JavaScript
2,024
star
2

isomorphic-react-example

Deprecated! ReactJS + NodeJS ( express ) demo tutorial with video. Universal/Isomorphic JS = Shared JavaScript that runs on both the client & server.
JavaScript
1,692
star
3

markdown-magic

πŸ’«  Automatically format markdown files using comment blocks. Update contents via custom transforms, external data sources & your source code.
JavaScript
785
star
4

netlify-functions-workshop

Netlify Serverless Functions Workshop
JavaScript
335
star
5

advanced-markdown

Learn about advanced markdown techniques
JavaScript
283
star
6

serverless-workshop

βš‘οΈβ€‚Open source serverless workshop. Ready to deploy serverless examples on AWS
JavaScript
184
star
7

responsible

Responsible.js - Give visitors the mobile experience THEY want
JavaScript
164
star
8

serverless-auth-strategies

How to handle authentication with serverless functions
JavaScript
137
star
9

types-with-jsdocs

Using JSDoc for Typescript Types
JavaScript
128
star
10

awesome-stoicism

πŸ’†β€β™‚οΈβ€‚Stoic philosophy resources
JavaScript
124
star
11

safe-await

Safely use async await without all the try/catch blocks
JavaScript
120
star
12

aws-profile-manager

GUI for managing AWS profile credentials.
JavaScript
58
star
13

atom-react-autocomplete

(Deprecated/Maintainer wanted) Atom Plugin for autocompleting react components & their props
JavaScript
55
star
14

next-with-react-router-v6

Next.js with React Router v6 demo
TypeScript
48
star
15

icon-pipeline

🚚 SVG icon pipeline - Optimize icons & build SVG sprites
JavaScript
45
star
16

pnpm-workspaces-example

PNPM workspaces example for monorepos
JavaScript
39
star
17

cache-me-outside

πŸ“ Caching tool for quicker builds in CI systems
JavaScript
37
star
18

react-router-tutorial

Learn how to add routing to your React App
JavaScript
30
star
19

serverless-manifest-plugin

Output manifest of endpoints, resources, outputs, etc. of a serverless service
JavaScript
27
star
20

video-app

πŸ‘¨β€πŸ’» Electron App for showing your webcam in a window thats always on top
JavaScript
26
star
21

react-server-components

Example of react server components running in AWS Lambda deployed via serverless framework
JavaScript
24
star
22

easy-markdown

WordPress Plugin to support Github Flavored Markdown + Syntax Highlighting
PHP
24
star
23

npm-statistics

NPM Download Statistics for David's Open Source Projects
JavaScript
21
star
24

configorama

βš™οΈ ${variable} support for config files
JavaScript
20
star
25

dom-guard

πŸ” Lock DOM node contents to protect people against scammers using browser devtools
HTML
19
star
26

davidwells.io

πŸŒβ€‚David's personal website
JavaScript
17
star
27

middy-example

Serverless project using middy middleware for so fresh & so clean clean lambdas πŸ›€
JavaScript
14
star
28

markdown-magic-github-contributors

markdown-magic Plugin to list out the contributors of your repository.
JavaScript
13
star
29

react-project-base

Super old. Do not use. My base for starting React Projects
JavaScript
12
star
30

aws-profile-cli

πŸ’» CLI & Utils for managing AWS accounts on your machine
JavaScript
12
star
31

intro-to-react

Introduction to React Core Concepts
JavaScript
12
star
32

netlify-site-as-aws-custom-resource-example

Define Netlify sites as part of an AWS Cloudformation stack.
JavaScript
11
star
33

function-zips

Using zip based functions in Netlify
HTML
11
star
34

use-analytics-with-react-router-demo

Use analytics react hooks with React Router v6
JavaScript
9
star
35

davidwells-legacy-site

πŸ‘΄ David's old personal site
JavaScript
9
star
36

react-example-project

JavaScript
8
star
37

env-stage-loader

Loads .env files in order based on process.env.NODE_ENV value with [stage].local support
JavaScript
8
star
38

oparser

A very forgiving key-value option parser
JavaScript
6
star
39

redux-toolkit-vite-example

TypeScript
6
star
40

netlify-sentry-plugin

WIP - Plugin to automatically run sentry releases
JavaScript
6
star
41

redux-tutorial

JavaScript
6
star
42

debug-plugin-activation-errors

Plugin for Debugging WordPress Plugin Activation Errors. Instead of seeing: "The plugin generated ### characters of unexpected output during activation. If you notice β€œheaders already sent” messages, problems with syndication feeds or other issues, try deactivating or removing this plugin." you get the errors being thrown.
PHP
6
star
43

react-autocomplete-cli

CLI companion to the atom-react-autocomplete plugin
JavaScript
4
star
44

happiness-as-a-service

Happiness as a serverless service
JavaScript
4
star
45

js-code-search

Quick links to find how people use npm packages.
JavaScript
4
star
46

scope

πŸ”­ Scope - Create a birdeye's view of your Github project and embed on your site
JavaScript
4
star
47

google-tag-manager-serverless

TODO serverlessify google tag manager serverside implementation
JavaScript
4
star
48

node-docker-workflow

Node Docker Continuous Integration with Express + Redis
Shell
3
star
49

Next-JS-Landing-Page-Starter-Template

next template with tailwind jit & webpack 5
TypeScript
3
star
50

next-with-react-router-v5

Using Next.js as SPA with react router v5
TypeScript
3
star
51

lerna-example

Lerna example for monorepos
JavaScript
3
star
52

repo-using-markdown-magic

Example of repo using markdown magic
JavaScript
3
star
53

analytics-e2e-testing

WIP analytics testing via Cypress
JavaScript
3
star
54

npm-workspaces-example

NPM workspaces example for monorepos
JavaScript
3
star
55

calm

Check if person is calm or not with javascript
JavaScript
3
star
56

explorer-demo-with-video

2
star
57

whats-in-the-cache

Recursively lookup files in a (cache) directory & print a manifest
JavaScript
2
star
58

explorer-demo-weds-two

2
star
59

gitignore-utils

JavaScript
2
star
60

themeable-components-themes

CSS
2
star
61

test-repo-tues-two

HTML
2
star
62

js-library-starter-kit

JavaScript library starter kit for open source projects
JavaScript
2
star
63

parse-npm-script

Parse package.json "script" commands to see how they resolve
JavaScript
2
star
64

explorer-demo-tues-four

2
star
65

simple-supplier-distributor-tues

2
star
66

jsdoc-parser

Updated fork of dox
JavaScript
2
star
67

store-it

Store data in browser. Fallbacks for everythang
JavaScript
2
star
68

mono-repo-example

HTML
2
star
69

WordPress-UI

A CSS Framework and a Set of React Components that Implement WordPress UI
JavaScript
2
star
70

git-er-done

Notice! Moved! See link below...... Utility for dealing with modified, created, deleted files since a git commit.
JavaScript
2
star
71

ryan-wells-foundation

WordPress Site for Ryan Wells Foundation
PHP
1
star
72

my-new-uni

Vendia Universal Application
HTML
1
star
73

next-netlify-blog-starter

JavaScript
1
star
74

react-workshop

1
star
75

safe-chalk

🎨 Terminal colors. Wrapper for chalk package with easy enable/disable option.
JavaScript
1
star
76

react-angular-webpack

React + Angular using ES6 + webpack
JavaScript
1
star
77

vis-tree-demo

JavaScript
1
star
78

customerio-example

JavaScript
1
star
79

electron-dev-setup

Starter project for electron apps
JavaScript
1
star
80

demo-netlify-gated-sites-login-site

JavaScript
1
star
81

redact-logs

Redact sensitive env vars from logs & CLI output.
JavaScript
1
star
82

buslify

Show me da bus
JavaScript
1
star
83

awesomesauce

JavaScript
1
star
84

react-dom-primitives

React Base Dom Primatives
JavaScript
1
star
85

addon-api-example

Example Netlify Add-on API using Netlify functions
JavaScript
1
star
86

netlify-build-mono-repo-base-dir

Mono repo base dir issue https://github.com/homertherefore/netlify-monorepo-project
JavaScript
1
star
87

amplify-vs-cognito-sdk-bundle-size-test

Amplify vs Cognito SDK bundle size test
HTML
1
star
88

minimal-code-sandbox

JavaScript
1
star
89

begin-basic-crud-app

Begin app
HTML
1
star
90

vgs-vanilla-demo

HTML
1
star
91

themeable-components

Themable (at build) react components using CSS
JavaScript
1
star
92

react-router-fibonacci

Fibonacci Sequence with React Router
JavaScript
1
star
93

tiny-cognito

Get AWS Cognito creds to use with aws4fetch
JavaScript
1
star
94

install-github-dep

Git submodules without using submodules
JavaScript
1
star
95

test-repo-cxz

HTML
1
star
96

components

React Components
JavaScript
1
star
97

get-object-diff

JavaScript
1
star
98

react-meetup-demo

Real world react meetup demo!!!!!!!!
JavaScript
1
star
99

react-i18next-advanced

react-i18next with local storage fallback
JavaScript
1
star
100

old-analytics-example

[Old] Example site using `analytics` package
JavaScript
1
star