GithubHelp home page GithubHelp logo

css-modules / webpack-demo Goto Github PK

View Code? Open in Web Editor NEW
1.5K 28.0 180.0 192 KB

Working demo of CSS Modules, using Webpack's css-loader in module mode

Home Page: https://css-modules.github.io/webpack-demo/

JavaScript 80.55% CSS 19.45%

webpack-demo's Introduction

Codeship Status for css-modules/webpack-demo

CSS Modules Webpack Demo

A working demo of CSS Modules, using Webpack's css-loader in module mode.

Run the example

$ npm install
$ npm start & open http://localhost:8080

npm modules required for CSS modules

In this project's package.json file you find a lot of npm modules for this demo application. Since not all of them are required for the actual CSS modules features, we've created the following list to describe their purposes.

Required modules

The following modules are the only ones really needed to get started with CSS modules:

Module Description
Webpack Webpack (obviously...)
webpack-dev-server (Optional) Supports hotloading of changed files etc while developing
style-loader and css-loader style-loader and css-loader process your CSS files. css-loader is the loader that actual makes CSS modules work

To make CSS modules work with Webpack you only have to include the modules mentioned above and add the following loader to your webpack.config.js file:

. . .
{
  test: /\.css$/,
  loader: 'style!css-loader?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]' 
}
. . .

Optional modules

The following modules control the actual CSS processing. They are not CSS modules specific and can be used with both "regular" CSS and CSS modules:

Module Description
postcss-loader Allows execution of various CSS post processor in Webpack. Required for autoprefixer-core and postcss-color-rebeccapurple
autoprefixer-core Add vendor-prefixes to your css code (according to the GitHub page it is deprecated and should be replaced by autoprefixer
postcss-color-rebeccapurple Another CSS post processor. Only needed to support rebeccapurple color in CSS
extract-text-webpack-plugin Writes the CSS code processed by Webpack into an own CSS-file and not into the generated bundle JavaScript file.

Unrelated modules

This modules are only needed for the demo application:

Module Description
babel ESx-to-ES5 compiler. Mostly needed for React code
ejs JavaScript templating language
react-to-html-webpack-plugin Webpack plug-in that renders React components
node-libs-browser Node libraries for in-browser use
gh-pages Publishes file to a gh-pages branches for GitHub pages
url-loader Webpack file handling, e.g. for images
file-loader Webpack file handling, e.g. for images
raw-loader It’s used to load raw css files (as utf8) into the demo so it can be rendered into <code>

License

MIT

webpack-demo's People

Contributors

basarat avatar lengarvey avatar markdalgleish avatar nilshartmann avatar sokra avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

webpack-demo's Issues

source maps?

Are there source maps that get generated in this project? That's the one thing that is making me hesitant to switch.

Doesn't work on Windows?

Not sure if this is Windows specific, actually, but here's what I see when I do npm start and open http://localhost:8080 in Chrome (Incognito).

webpack-demo

Are there instructions missing from the readme?

webpack config question/issue

Hi there, setting myself up for universal react render using css-modules and webpack. Coming across a strange issue I don't understand, due to limited experience with webpack:

On this line in the webpack config in this repo, why will webpack fail if I modify it simply to try to list the ExtractTextPlugin as one of multiple loaders for css?

{ test: /\.css$/, loaders: [ ExtractTextPlugin.extract('style-loader', 'css-loader?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]!postcss-loader') ] },

Gives me Error: Cannot find module "./App.css" ...

Cheers

How to run without react.js?

Great work, really useful.
I am writing code using webpack+babel but without react.js.
Can you post an example of what are the minimal package needed to use module mode css?

Thanks!

Dev server doesn't work

I was hoping to get this up and running to quickly iterate on some css-module experiments. It seems the npm start task is broken. I see webpack-dev-server start but when I browse to localhost:8080 there is nothing served.

The build seems to be broken?

 |master ✓| → npm start

> [email protected] start /Users/dmitrizaitsev/Repos/webpack-demo
> webpack-dev-server

http://localhost:8080/webpack-dev-server/
webpack result is served from /
content is served from /Users/dmitrizaitsev/Repos/webpack-demo
/Users/dmitrizaitsev/Repos/webpack-demo/node_modules/webpack-dev-middleware/middleware.js:106
            if(err) throw err;
                    ^

Error: Output file not found: "index.js"
    at ReactToHtmlWebpackPlugin.<anonymous> (/Users/dmitrizaitsev/Repos/webpack-demo/node_modules/react-to-html-webpack-plugin/index.js:19:15)
    at Compiler.applyPluginsAsync (/Users/dmitrizaitsev/Repos/webpack-demo/node_modules/tapable/lib/Tapable.js:71:13)
    at Compiler.emitAssets (/Users/dmitrizaitsev/Repos/webpack-demo/node_modules/webpack/lib/Compiler.js:226:7)
    at Watching.<anonymous> (/Users/dmitrizaitsev/Repos/webpack-demo/node_modules/webpack/lib/Compiler.js:54:18)
    at /Users/dmitrizaitsev/Repos/webpack-demo/node_modules/webpack/lib/Compiler.js:403:12
    at Compiler.next (/Users/dmitrizaitsev/Repos/webpack-demo/node_modules/tapable/lib/Tapable.js:67:11)
    at Compiler.<anonymous> (/Users/dmitrizaitsev/Repos/webpack-demo/node_modules/webpack/lib/CachePlugin.js:40:4)
    at Compiler.applyPluginsAsync (/Users/dmitrizaitsev/Repos/webpack-demo/node_modules/tapable/lib/Tapable.js:71:13)
    at Compiler.<anonymous> (/Users/dmitrizaitsev/Repos/webpack-demo/node_modules/webpack/lib/Compiler.js:400:9)
    at Compilation.<anonymous> (/Users/dmitrizaitsev/Repos/webpack-demo/node_modules/webpack/lib/Compilation.js:577:13)

npm ERR! Darwin 12.6.0
npm ERR! argv "/usr/local/bin/node" "/Users/dmitrizaitsev/.npm-global/bin/npm" "start"
npm ERR! node v4.2.4
npm ERR! npm  v3.5.3
npm ERR! code ELIFECYCLE
npm ERR! [email protected] start: `webpack-dev-server`
npm ERR! Exit status 1
npm ERR! 
npm ERR! Failed at the [email protected] start script 'webpack-dev-server'.
npm ERR! Make sure you have the latest version of node.js and npm installed.
npm ERR! If you do, this is most likely a problem with the webpack-demo package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     webpack-dev-server
npm ERR! You can get information on how to open an issue for this project with:
npm ERR!     npm bugs webpack-demo
npm ERR! Or if that isn't available, you can get their info via:
npm ERR!     npm owner ls webpack-demo
npm ERR! There is likely additional logging output above.

npm ERR! Please include the following file with any support request:
npm ERR!     /Users/dmitrizaitsev/Repos/webpack-demo/npm-debug.log

Question about using with sass loader

Is there a clean way to use this in tandem with Sass-Loader? I would like to use my mixins and variables but still keep my classes namespaced locally.

Explaining the modules

For a beginner the amount of modules this demo requires might be overwhelming without a proper explanation. I myself had to go through each of them and look them up to get a rough idea what exactly I need to run CSS Modules with webpack.
A short explanation in the Readme how they work together might be helpful to get people started more easily.
I would do it myself but I still haven't grasped the whole thing.

[HMR] CSS vanishes on hot reload

So I am using this with HMR. I got everything working fine when I firstly load the app. But when I change something in my css file, I get an update in the app but the styles are not replaced with the new information but the class just vanishes from the head section of the html. I have to F5 to reload the page and the styles are added in the head section again.

It looks to me as if on update the css is removed from the head but not added again. I understand that this issue might be unrelated to this specific package, but I thought it might be worth while starting to ask here.

webpack.config.babel.js

import path from 'path'
import webpack from 'webpack'
import HtmlWebpackPlugin from 'html-webpack-plugin'
export default {
  entry: {
    preview: './src/preview/index.jsx'
  },
  output: {
    path: path.join(__dirname, 'preview'),
    filename: '[name].js',
    publicPath: 'http://localhost:4000/'
  },
  module: {
    rules: [
      {
        test: /\.jsx?$/,
        exclude: /node_modules/,
        use: [
          {
            loader: 'babel-loader',
            options: {
              presets: [ [ "es2015", { "modules": false } ], "stage-2", "react" ]
            }
          }
        ]
      },
      {
        test: /\.json$/,
        loader: 'json-loader'
      },
      {
        test: /\.hbs$/,
        loader: 'handlebars-loader'
      },
      {
        test: /\.scss$/,
        use: [
          'style-loader',
          { loader: 'css-loader', options: { modules: true } },
          'sass-loader'
        ]
      },
      {
        test: /\.css$/,
        use: [
          'style-loader',
          { loader: 'css-loader', options: { modules: true } }
        ]
      },
      {
        test: /\.less$/,
        use: [
          'style-loader',
          { loader: 'css-loader', options: { importLoaders: 1 } },
          'less-loader'
        ]
      }
    ]
  },
  resolve: {
    extensions: ['.js', '.jsx']
  },
  plugins: [
    new webpack.ProvidePlugin({
      $: 'jquery',
      jQuery: 'jquery'
    }),
    new HtmlWebpackPlugin({
      title: 'Static Preview SatoshiPay Widget',
      template: `${__dirname}/index.ejs`
    }),
    new webpack.HotModuleReplacementPlugin(),
    // enable HMR globally
    new webpack.NamedModulesPlugin(),
    // prints more readable module names in the browser console on HMR updates
  ],
  devServer: {
    port: 4000,
    stats: 'minimal',
    host: 'localhost',
    hot: true
  },
  devtool: 'inline-source-map'
}

devDeps from package.json:

  "devDependencies": {
    "async": "^2.1.5",
    "autoprefixer": "^6.7.3",
    "babel-cli": "^6.18.0",
    "babel-core": "^6.21.0",
    "babel-eslint": "^7.1.1",
    "babel-loader": "^6.3.2",
    "babel-plugin-syntax-dynamic-import": "^6.18.0",
    "babel-polyfill": "^6.20.0",
    "babel-preset-es2015": "^6.18.0",
    "babel-preset-node6": "^11.0.0",
    "babel-preset-react": "^6.16.0",
    "babel-preset-stage-2": "^6.22.0",
    "babel-register": "^6.23.0",
    "babelify": "^7.2.0",
    "browser-sync": "^2.9.8",
    "browserify": "^14.1.0",
    "chai": "^3.5.0",
    "chai-as-promised": "^6.0.0",
    "css-loader": "^0.26.1",
    "deep-freeze": "^0.0.1",
    "del": "^2.2.2",
    "dotenv": "^4.0.0",
    "electron": "^1.4.15",
    "envify": "^4.0.0",
    "eslint": "^3.14.1",
    "eslint-plugin-react": "^6.9.0",
    "event-stream": "^3.3.2",
    "expect": "^1.20.2",
    "extract-text-webpack-plugin": "^2.0.0",
    "file-loader": "^0.10.1",
    "finalhandler": "^1.0.0",
    "flow-bin": "^0.40.0",
    "git-rev-sync": "^1.8.0",
    "glob": "^7.0.3",
    "gulp-standard": "^9.0.0",
    "handlebars": "^4.0.6",
    "handlebars-loader": "^1.4.0",
    "html-webpack-plugin": "^2.26.0",
    "json-loader": "^0.5.4",
    "karma": "^1.4.0",
    "karma-babel-preprocessor": "^6.0.1",
    "karma-chai": "^0.1.0",
    "karma-chrome-launcher": "^2.0.0",
    "karma-coverage": "^1.1.1",
    "karma-electron": "^5.1.1",
    "karma-junit-reporter": "^1.2.0",
    "karma-mocha": "^1.3.0",
    "karma-phantomjs-launcher": "^1.0.2",
    "karma-sourcemap-loader": "^0.3.7",
    "karma-spec-reporter": "^0.0.30",
    "karma-webpack": "^2.0.2",
    "less": "^2.7.2",
    "less-loader": "^2.2.3",
    "mocha": "^3.2.0",
    "mocha-loader": "^1.1.0",
    "mock-local-storage": "^1.0.2",
    "node-sass": "^4.5.0",
    "phantomjs-polyfill": "^0.0.2",
    "postcss-loader": "^1.2.2",
    "postcss-smart-import": "^0.6.7",
    "precss": "^1.4.0",
    "promise-polyfill": "^6.0.2",
    "react-hot-loader": "next",
    "sass-loader": "^6.0.2",
    "selenium-webdriver": "^3.0.1",
    "serve-static": "^1.9.3",
    "source-map-support": "^0.4.11",
    "standard": "^9.0.0",
    "style-loader": "^0.13.1",
    "uglifyify": "^3.0.1",
    "vinyl-source-stream": "^1.1.0",
    "watchify": "^3.1.2",
    "webpack": "^2.2.1",
    "webpack-dev-server": "^2.4.1"
  }

Question: sass support

I am trying to use css modules with webpack and this demo has been super helpful to get me started.
Is there a way to add sass loader with css modules?

Demo out of date?

Last updated 2 years ago. I'm unsuccessfully trying to add css-modules to a simple project.

ERROR in ./src/client/app/index.jsx
Module not found: Error: Can't resolve 'style' in '/Library/WebServer/Documents/www.mike-austin.com/models'
BREAKING CHANGE: It's no longer allowed to omit the '-loader' suffix when using loaders.
You need to specify 'style-loader' instead of 'style',
see https://webpack.js.org/guides/migrating/#automatic-loader-module-name-extension-removed
@ ./src/client/app/index.jsx 13:14-37

Unit tests

How would you do unit tests with css-modules / css-loader?

I love the idea of css-modules but am struggling with testing as node cannot require css. I'm very thankful for any answer or idea.

bad error catch

if there is a error of syntax like

return <div className={styles.logo} >;
or
return <div className={styles.logo)} />;

the server just be broken!

Hot reloading css

Hi, first of all thanks for the awesome work on css-modules! I'm trying it out now on a new personal project.

I want to achieve hot reloading of the css with css-modules, but I'm not quite sure what the right setup would be. Is this something you have played around with?

Outdate!

nvalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema.

  • configuration has an unknown property 'postcss'. These properties are valid:
    object { amd?, bail?, cache?, context?, dependencies?, devServer?, devtool?, entry, externals?, loader?, module?, name?, node?, output?, parallelism?, performance?, plugins?, profile?, recordsInputPath?, recordsOutputPath?, recordsPath?, resolve?, resolveLoader?, stats?, target?, watch?, watchOptions? }

ReferenceError for console and window objects

Great demo! I get errors which I don't understand when I add browser related Objects to index.js

  1. I run the demo with npm start
  2. If I add window.React = React; to src/index.js I get this error:
webpack: bundle is now INVALID.
evalmachine.<anonymous>:80
    console.log('hello');
    ^
ReferenceError: console is not defined
    at Object.<anonymous> (evalmachine.<anonymous>:80:2)
    at __webpack_require__ (evalmachine.<anonymous>:30:30)
    at Object.defineProperty.value (evalmachine.<anonymous>:50:18)
    at evalmachine.<anonymous>:53:10
    at webpackUniversalModuleDefinition (evalmachine.<anonymous>:3:20)
    at evalmachine.<anonymous>:10:3
    at ContextifyScript.Script.runInNewContext (vm.js:18:15)
    at module.exports (/private/tmp/webpack-demo/node_modules/react-to-html-webpack-plugin/node_modules/eval/eval.js:56:8)
    at ReactToHtmlWebpackPlugin.<anonymous> (/private/tmp/webpack-demo/node_modules/react-to-html-webpack-plugin/index.js:21:23)
    at Tapable.applyPluginsAsync (/private/tmp/webpack-demo/node_modules/webpack/node_modules/tapable/lib/Tapable.js:71:13)

Adding console.log('hello'); causes a similar error. What might cause this?

I'm asking because I would like to use this demo as a base for a project.

Document example of :local

I’m still not sure what :local does exactly or what kind of scenario it would be helpful in. Another example would help.

I’m also trying to figure out how to share a "family" of classes without too much boilerplate code. An example would be an <input> that shares valid/required/error/etc. states across an app. Currently you can easily import directly from a shared/input.css and use those classnames, but as soon as you want to customize one state for that component (say; increase the size) your composed classname won’t pick up all the other definitions (.valid, .error, etc.). I guess the solution here would be to not compose and just use multiple classnames?

mistake in README

Webpack configuration is wrong. After adding

loader: 'style!css-loader?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]'

i have error:
ERROR in ./src/App.jsx Module not found: Error: Can't resolve 'style' in 'C:\projects\transEdu_04.2-test\transEdu-carriersRanking'

-src
--app.jsx
--css
---style.css

in app.jsx:


.
.
.
import styles from './css/style.css';
.
.
.
<div className={styles.test}>test</div>

How to make jest test the scss?

I am getting the 'src/components/HelloComponent/Hello.scss: Unexpected token .'

import React from 'react';
import styles from './Hello.scss';

How to make jest test the scss?

Ignoring css from the other libraries in node modules

Hi,

I am using a javascript plugin and its default stylesheets (by referring from the node_modules directory). When I enable the css modules, even the stylesheets referred from the directory gets locally scoped with hash. However, the class names from this plugin does not reflect the scoped names within the HTML, for obvious reasons that the plugin hasn't been written the css modules.

How can I ignore scoping of the stylesheets coming from the node_modules? Or what is the best way for the current scenario?

Thanks in advance!

Can webpack aliases be supported?

in my VS code,The plugin support supports relative paths,but not supports webpack ailas '@'

Can you support this feature by adding configuration?

Thank you very much!

Does this work with Webpack's HMR

Great starter repo. I really love CSS Modules! Curious if this works with Wepack's HMR. I'm not able to get it to work. Thanks again!

Error with webpack 2.1.0-beta.27

A chunk of the error output

oo/node_modules/loader-runner/lib/loadLoader.js:35
			throw new Error("Module '" + loader.path + "' is not a loader (must have normal or pitch function)");
			^

Error: Module 'xxx' is not a loader (must have normal or pitch function)

problem with composing classes from global

Do you know what's wrong with the following piece of code?
it doesn't work.

/* style.css */
:global .globalText {
  color: green;
}
/* otherStyle.css */
.text {
  composes: globalText from global;
  background-color: #777;
}

Error in compilation cussed by the "composes:..." line :

webpack: Compiling...
Error: Cannot find module "./otherStyle.css"

But when i comment out that line it compiles without any errors.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.