Coder Social home page Coder Social logo

cultureamp / elm-css-modules-loader Goto Github PK

View Code? Open in Web Editor NEW
71.0 58.0 12.0 917 KB

Reference CSS modules in Elm source files with Webpack

License: BSD 3-Clause "New" or "Revised" License

CSS 1.28% Elm 54.26% JavaScript 42.33% HTML 2.12%
elm-lang webpack-loader css-modules css webpack elm

elm-css-modules-loader's Introduction

CSS Modules for Elm

A Webpack loader that enables you to reference CSS modules in Elm source files.

Hat tip to NoRedInk and its elm-assets-loader, which formed the technical basis for this package.

Overview

Start with a CSS file that can be imported by Webpack using css-loader:

.something {
  ⋮
}

.anotherThing {
  ⋮
}

In any Elm module, reference this stylesheet and the classes you want to use in it:

module Main exposing (..)

import CssModules exposing (css)


styles =
    css "./stylesheet.css" -- relative to main Elm source directory
        { something = "something" -- string value should match CSS class name 
        , anotherThing = "anotherThing"
        }

Then use the returned functions to use the class names in your view:

view : Html Msg
view =
    div
        [ styles.class .something ]
        [ text "this is a div"]

Note: the .something syntax may be confusing at first. This is just standard Elm syntax for a function that reaches into a record and returns the value of the something key. Because the Elm compiler will only let you reference class names that exist in your CSS Module declaration, you get a bit of type safety to guard against typing mistakes.

Why does this exist?

We wanted to use the same style sheets for the standard components in our application (buttons, form fields, etc.) across two different implementations of these components (React and Elm). We love the namespacing and composition features of CSS Modules; this project seeks to make them usable within Elm views.

Note: elm-css is the de facto standard for writing styles for HTML interfaces written in Elm. If you are working on an all-Elm application, you should probably use that.

How to use

To get this working, you need to set up a combination of a Webpack loader and and Elm package.

Webpack Loader

Add the elm-css-modules-loader NPM package to your project, then configure Webpack to chain it with elm-webpack-loader:

Webpack 2+

module.exports = {
  
  module: {
    rules: [
      {
        test: /\.elm$/,
        use: [
          {
            loader: 'elm-css-modules-loader',
          },
          {
            loader: 'elm-webpack',
          }
        ],
      },
      
    ],
  },
};

Webpack 1.x

module.exports = {
  
  module: {
    loaders: [
      {
        test: /\.elm$/,
        loaders: [
          'elm-css-modules-loader',
          'elm-webpack',
        ],
      },
      
    ],
  },
};

Note the following configuration options are available for the loader. If you’re using the original version of this package, the defaults should work fine.

package – (default: cultureamp/elm-css-modules-loader) The Elm package in which the CssModule type is defined. If you forked the Elm package for your own development, you’ll need to specify the full package name that you have released it under with this option.

module – (default: CssModules) The name of the Elm module in which the tagger function is defined.

tagger – (default: css) The name of the Elm factory function that is used to declare CssModules in your code.

Note: Don't set noParse on .elm files. Otherwise, the JavaScript requires that this loader adds to your compiled Elm modules won't be processed by Webpack.

Elm Package

Install the cultureamp/elm-css-modules-loader package in your Elm project, then use the CssModule constructor for referencing CSS modules.

Under the hood

Let’s walk through what happens when this Elm code is processed by Webpack:

styles =
    css "./stylesheet.css"
        { something = "something"
        , anotherThing = "anotherThing"
        }

This will be compiled to JavaScript by elm-webpack-loader:

var user$project$Styles$styles = A2(
  cultureamp$elm_css_modules_loader$CssModules$css,
  './stylesheet.css',
  {
    aC: 'something',
    aD: 'anotherThing'
  }
);

elm-css-modules-loader replaces the hard-coded JSON object with a require of your stylesheet:

var user$project$Styles$styles = A2(
  cultureamp$elm_css_modules_loader$CssModules$css,
  './stylesheet.css',
  {
    aC: require('./stylesheet.css')["something"],
    aD: require('./stylesheet.css')["anotherThing"]
  }
);

webpack parses this require call, processes the stylesheet with css-loader, and replaces the require with a reference to the CSS module:

var user$project$Styles$styles = A2(
  cultureamp$elm_css_modules_loader$CssModules$css,
  './stylesheet.css',
  {
    aC: __webpack_require__(42)["something"],
    aD: __webpack_require__(42)["anotherThing"]
  }
);

The CSS module loaded by __webpack_require__(42) contains the actual class names that your Elm app will now consume:

42:
function(module, exports) {
  module.exports = {
    something: 'something-abc123',
    anotherThing: 'anotherThing-abc123'
  };
}

Changelog

Our release history is tracked on the Github Releases page.

Note that the NPM package and the Elm package will have different version numbers, as changes to the Elm API may happen indepently of changes to the NPM API, and Elm does not allow you to bump the version number without changes to the Elm API. When viewing the releases page, NPM releases are tagged with a "v" - v2.1.0. While Elm releases are tagged with no leading "v" - 2.0.3.

For release history prior to 2.0.2, you can view our old CHANGELOG .


Elm CSS Modules Loader is maintained by the Front End Capability Team at Culture Amp.

elm-css-modules-loader's People

Contributors

asaayers avatar backstage-culture-amp[bot] avatar ckychris avatar dan-lennox avatar jasononeil avatar michaeljones avatar semantic-release-bot avatar sentience avatar zioroboco 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

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  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

elm-css-modules-loader's Issues

Add Webpack 4 support

We aren’t aware of any specific compatibility issues with this loader and Webpack 4, but we haven’t yet tested it extensively, and so the current release still specifies webpack <4 in its peerDependencies.

We’d appreciate hearing from anyone who’s tried this loader with Webpack 4 and is able to report on how/if it worked for them. If not, we will eventually update this ourselves when we upgrade to Webpack 4.

The automated release is failing 🚨

🚨 The automated release from the master branch failed. 🚨

I recommend you give this issue a high priority, so other packages depending on you could benefit from your bug fixes and new features.

You can find below the list of errors reported by semantic-release. Each one of them has to be resolved in order to automatically publish your package. I’m sure you can resolve this 💪.

Errors are usually caused by a misconfiguration or an authentication problem. With each error reported below you will find explanation and guidance to help you to resolve it.

Once all the errors are resolved, semantic-release will release your package the next time you push a commit to the master branch. You can also manually restart the failed CI job that runs semantic-release.

If you are not sure how to resolve this, here is some links that can help you:

If those don’t help, or if this issue is reporting something you think isn’t right, you can always ask the humans behind semantic-release.


Invalid npm token.

The npm token configured in the NPM_TOKEN environment variable must be a valid token allowing to publish to the registry https://registry.npmjs.org/.

If you are using Two-Factor Authentication, make configure the auth-only level is supported. semantic-release cannot publish with the default auth-and-writes level.

Please make sure to set the NPM_TOKEN environment variable in your CI with the exact value of the npm token.


Good luck with your project ✨

Your semantic-release bot 📦🚀

NPM module installed recursively in example directory

When I npm install in the example directory, I've noticed that the module is installed inside itself recursively (elm-css-modules-loader/example/node_modules/elm-css-modules-loader/example/node_modules/elm-css-modules-loader/example/node_modules/…), and that this is probably not intended or desirable.

Add Webpack 2.0 support

@sentience this is super duper cool! Thanks for providing it! I noticed in the ReadMe that Webpack 2.0 support is at the top of the priority list. I wanted to follow progress right away, but I didn't find an issue for it, so I made this one. I hope that's okay!

class undefined

Hi,
I followed the instructions, but still showing class is undefined in chrome inspect tools.
the code in style.css
.list { background-color: yellow; }
The webpack config file
module: { rules: [{ test: /\.elm$/, use: [{ loader: 'elm-css-modules-loader', }, { loader: 'elm-webpack-loader', } ], }, { test: /\.css$/, use: ['style-loader', 'css-loader?modules=true'], }, ], },

The Main.elm file
`import Browser
import Html exposing (..)
import Html.Attributes exposing (..)
import Html.Events exposing (onClick)
import CssModules exposing (css)

styles =
css "../style.css" -- relative to main Elm source directory
{ list = "list" -- string value should match CSS class name
,another = "another"
}
main =
Browser.element {init = init, update = update, view = view, subscriptions = subscriptions}

-- MODEL

type alias ToDo =
{description: String
,completed: Bool
,editing: Bool
,id: Int}

type alias Model = Maybe (List ToDo)
init : () -> (Model, Cmd msg)
init _ =
(Just [{
description="hahaha"
,completed= False
,editing=False
,id=1},
{
description="xixixi"
,completed= False
,editing=False
,id=2}]
,Cmd.none)

-- UPDATE

type Msg = Increment | Decrement | Reset

update : msg->Model->(Model, Cmd msg)
update msg model=
(model,Cmd.none)
-- VIEW

view : Model -> Html msg
view todolist =

case todolist of
  Just a ->
    --below cannot be written as ui[][List.map xxxx], has to use <|.
    Debug.log (Debug.toString (styles.class .list))
    ul[styles.class .list] <| List.map (\x -> li[][text x.description]) a
   
  Nothing ->
    div[styles.class .list][text "nothing"]

subscriptions : Model -> Sub msg
subscriptions model =
Sub.none`

Seems everything is right, have no idea why the class is undefined.
Please help, Thanks.

Upgrade to Elm 0.19

We love this library and we're hoping to update to Elm 0.19 as I'm sure you are too. Do you know if the approach with this module & webpack loader will continue to work in Elm 0.19 yet?

Can I be of any assistance with the update? I'm not hugely experienced but keen to help!

Thanks.

hypens

was trying to migrate some existing css and although its easy to use hyphens in the elm string it blows up on the hyphen when translated to js.

fixedTop: require("./WelcomePage.module.css").fixed-top,

The automated release is failing 🚨

🚨 The automated release from the master branch failed. 🚨

I recommend you give this issue a high priority, so other packages depending on you could benefit from your bug fixes and new features.

You can find below the list of errors reported by semantic-release. Each one of them has to be resolved in order to automatically publish your package. I’m sure you can resolve this 💪.

Errors are usually caused by a misconfiguration or an authentication problem. With each error reported below you will find explanation and guidance to help you to resolve it.

Once all the errors are resolved, semantic-release will release your package the next time you push a commit to the master branch. You can also manually restart the failed CI job that runs semantic-release.

If you are not sure how to resolve this, here is some links that can help you:

If those don’t help, or if this issue is reporting something you think isn’t right, you can always ask the humans behind semantic-release.


A publish plugin returned an invalid value. It must return an Object.

The publish plugins must return an Object.

The publish function of the ./ci/publishElmRelease.js returned true instead.

We recommend to report the issue to the ./ci/publishElmRelease.js authors, providing the following informations:


Good luck with your project ✨

Your semantic-release bot 📦🚀

Getting example app to work?

Hi, I tried to run example app to see the exact output, but couldn't get it working.

I tried:

git clone [email protected]:cultureamp/elm-css-modules-loader.git
cd elm-css-modules-loader/example
yarn
elm-live elm-app/Main.elm

The app compiles and launches successfully. I can see the texts, but styles were not applied. Is there something I'm missing? I also tried elm reactor but it had identical result.

I'm using Elm 0.19 and NodeJS 9.0 on Ubuntu 16.04

Question, can use nested classes

Hi,

Just curious if the loader can handle nested classes like
Btw this loader is amazing, using it with stylus right now and create elm app and never had to eject 💃

.one
   .two

Question

this isn't an issue, just a question

will this apply everything configured in the css pipline, i.e. postcss, autoprefixer?

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.