Coder Social home page Coder Social logo

michalkvasnicak / babel-plugin-css-modules-transform Goto Github PK

View Code? Open in Web Editor NEW
325.0 9.0 54.0 266 KB

Extract css class names from required css module files, so we can render it on server.

License: MIT License

JavaScript 97.22% Shell 2.37% CSS 0.41%
css-modules babel-plugin babel extract-css css-files preprocessor

babel-plugin-css-modules-transform's Introduction

Hi there πŸ‘‹

I'm Michal KvasničÑk a full stack engineer from πŸ‡ΈπŸ‡°. I ❀️ React, GraphQL, Node.js, Typescript...

I know this README is boring, what'd you like to know? Ask me anything!

babel-plugin-css-modules-transform's People

Contributors

gabemedrash avatar jakxz avatar jmurzy avatar jvivs avatar leoasis avatar levity avatar michalkvasnicak avatar omgimalexis avatar pascalduez avatar smelukov avatar ziad-saab 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

babel-plugin-css-modules-transform's Issues

Scss for loops prevent class name exports

As I've seen, scss for loops completely prevent any classes from getting exported.

I know this isn't babel-plugin-scss-modules-transform, but I'm wondering if anyone has encountered this and if there is solution.

I ended up removing the for loop and explicitly defining every class. I also tried to define all the class names but still having the for loop. Neither of those things work. As soon as there is for loop you can't extract class names.

what's the recommended way to disable this within babelrc when compiling via webpack?

Currently, I'm duplicating my babelrc in my webpack config with babelrc: false like this:

test: /\.js$/,
        exclude: /node_modules|extract-text-webpack-plugin/,
        use: {
          loader: 'babel-loader',
          options: {
            babelrc: false,
            presets: ['es2015', 'react', 'stage-2'],
            plugins: [
              require('babel-plugin-dynamic-import-webpack').default,
              require('react-hot-loader/babel'),
            ],
          },
        },

But ultimately that's really cumbersome, especially when what I'm doing is recommending the use of babel-plugin-css-modules-transform for use in conjunction with my package. It means a lot of extra directions to provide developers, when otherwise things are very simple.

I've tried things like using the ignore option using a function to no avail. It would be nice if it could be disabled with the present of a particular environment variable, such as:

process.env.IS_WEBPACK === true

via an option like:
disableOnEnv: "IS_WEBPACK".

Perhaps there is already something like this? I think a lot of people use this webpack--so an idiomatic strategy documented for that would be very useful.

Composing from another file results in undefined

given some css like this:

.base {
  composes: inline-block from '../styles.css';
  color: red;
}

.babelrc like this:

"plugins": [
        ["css-modules-transform", { "generateScopedName": "test_[name]__[local]" }]
    ]

the plugin outputs this:

var _button = {
    'base': 'test_component__base undefined',
}

Babel-cli watch mode

I tried using this together with the babel-cli and it does only extract the CSS when it is run the first time, every later change is not picked up even though babel does transpile the .js files.

I did try enable the devMode but it did not work.

Using this plugin for Library with extractCSS option

I am creating a library and each component will import its respective CSS which needs to be CSS-Modularized.

I am also using the following config in .babelrc

                [
                    "css-modules-transform", 
                    {
                        "preprocessCss": "./config/babel-sass-loader.js",
                        "generateScopedName": "[name]_[local]_[hash:base64:5]",
                        "extensions": [".css", ".scss"],
                        "ignore": "*/styles/*",
                        "extractCss": {
                            "dir": "./dist/",
                            "relativeRoot": "./src/",
                            "filename": "[path]/[name].scss"
                        }                
                    }
                ]

After running babel-cli, I see that the CSS files are having scoped names and the JS file also has the mapping between original name to scoped name. However, the generated JS doesnt have the import anymore to the processed CSS file. This is because of the line https://github.com/michalkvasnicak/babel-plugin-css-modules-transform/blob/master/src/index.js#L152.

Without this link through import, the consumers of this library doesnt get the CSS definitions. Am I missing some config?

Cache issues with CSS

For some unknown reason extracted CSS is only saved to disk once. All subsequent changes to CSS are no-op.

NODE_ENV is set to development.

Config:

{
  "presets": ["es2015", "stage-0", "react"],
  "plugins": ["transform-decorators-legacy", "transform-runtime", [
    "css-modules-transform", {
      "extractCss": "./build/assets/style.compiled.css",
      "devMode": true
    }
  ]]
}

This is the log from browser-sync:

[BS] File changed: build/components/Login.css
[BS] File changed: build/assets/style.compiled.css
app/components/Login.js -> build/components/Login.js
[BS] File changed: build/components/Login.js.map
[BS] File changed: build/components/Login.js
[BS] File changed: build/components/Login.css
app/components/Login.js -> build/components/Login.js
[BS] File changed: build/components/Login.js.map
[BS] File changed: build/components/Login.js
[BS] File changed: build/components/Login.css
[BS] File changed: build/components/Login.css
app/components/Login.js -> build/components/Login.js
[BS] File changed: build/components/Login.js.map
[BS] File changed: build/components/Login.js
app/components/Login.js -> build/components/Login.js
[BS] File changed: build/components/Login.js.map
[BS] File changed: build/components/Login.js
app/components/Login.js -> build/components/Login.js
[BS] File changed: build/components/Login.js.map
[BS] File changed: build/components/Login.js
app/components/Login.js -> build/components/Login.js
[BS] File changed: build/components/Login.css
[BS] File changed: build/components/Login.js.map
[BS] File changed: build/components/Login.js

screenshot 2017-02-08 12 43 54

I wrote a somewhat test to verify that there is no issue with CSS compiler. Looking at console output everything is alright.

it('should recompile generated file', () => {
    const called = [];
    const dir = `${__dirname}/output`;
    const input = `${dir}/input.css`;
    const output = `${__dirname}/output/output.css`;

    mkdirSync(dir);
    
    const sources = ['.class { color: red; }', '.class { color: blue; }', '.class { color: green; }'];

    for (const src of sources) {
        writeFileSync(input, src, { encoding: 'utf8' });

        const source = transform('fixtures/generated.js', {
            extractCss: output,
            processCss(css, filename) {
                called.push(relative(__dirname, filename));
                console.log(`PROCESSED ${filename}`);
                return css;
            }
        }).code;

        const generatedCSS = readFileSync(output, 'utf8');

        console.log(`!!! COMPILED:\n\n${source}\n\n!!!\n\n`);
        console.log(`!!! READ FILE: ${generatedCSS}`);
    }
});

I first run babel to precompile everything with the following options:

babel app/ --copy-files --out-dir build --source-maps true

Then I run two scripts in parallel:

Script that spins off Browser sync to reload browser on file changes:

babel-node scripts/serve.js

Babel with --watch option to recompile files on fly:

babel app/ --copy-files --out-dir build --source-maps true --watch --skip-initial-build

complexRequires (prepend) and specifics options

Hi again!

Today, i tested new released tag 0.0.8, with my prepend config:

"prepend": ["postcss-cssnext"], 

It Works πŸ‘

But, currently i can't pass specific opts for postcss-cssnext :

features: {
  customProperties: {
    variables: $properties,
  },
}

I don't know if your plugin is designed in order to do specifics configuration.
And i got some troubles with 'postcss-import' module because it seems to be async :
css-modules/css-modules-require-hook#58

Error: Cannot find preprocess script. (For sass in my case)

Have this configuration:

{
  "presets": ["es2015","stage-2","react"],
  "plugins": [
  "babel-plugin-webpack-alias",
    ["transform-object-rest-spread", { "useBuiltIns": true }],
    ["css-modules-transform",{
        "generateScopedName": "[name]__[local]___[hash:base64:5]",
        "preprocessCss": "./utils/sass_preprocess_tool.js",
        "extensions": [".css", ".scss"],
        "extractCss": "./dist/combined.css"
    }]
  ]
}

Using the exact script from the READ.me

// ./path/to/module-exporting-a-function.js
var sass = require('node-sass');
var path = require('path');

module.exports = function processSass(data, filename) {
    var result;
    result = sass.renderSync({
        data: data,
        file: filename
    }).css;
    return result.toString('utf8');
};

When using a relative file path get:

/home/pil0t/Projects/powr_x/node_modules/babel-cli/node_modules/babel-core/lib/transformation/file/index.js:600
      throw err;
      ^

Error: /home/pil0t/Projects/powr_x/src/api/server.js: Cannot find module './utils/sass_preprocess_tool.js'
    at Function.Module._resolveFilename (module.js:470:15)
    at Function.Module._load (module.js:418:25)
    at Module.require (module.js:498:17)
    at require (internal/module.js:20:19)
    at requireLocalFileOrNodeModule (/home/pil0t/Projects/powr_x/node_modules/babel-plugin-css-modules-transform/build/utils/requireLocalFileOrNodeModule.js:24:16)

When using absolute file path, get:

/home/pil0t/Projects/powr_x/node_modules/babel-cli/node_modules/babel-core/lib/transformation/file/index.js:578
        throw err;
        ^

Error: /home/pil0t/Projects/powr_x/utils/sass_preprocess_tool.js: Configuration file for 'preprocessCss' is not exporting a function
    at Object.preprocessCss (/home/pil0t/Projects/powr_x/node_modules/babel-plugin-css-modules-transform/build/options_resolvers/preprocessCss.js:25:15)
    at /home/pil0t/Projects/powr_x/node_modules/babel-plugin-css-modules-transform/build/index.js:131:66
    at Array.forEach (native)

Could this plugin work with babel-plugin-module-resolver?

Hi, I have a issue here. And this is my case.

.babelrc file

"plugins": [
  ["module-resolver", {
    "alias": {
      "assets": "./src/assets"
    }
  }],

  ["css-modules-transform", {
    "preprocessCss": "./preprocessCss.js",
    "camelCase": true,
    "generateScopedName": "[name]-[hash:16]",
    "extensions": [".scss"]
  }]
]

source file

import css from 'assets/stylesheets/basic/loading.scss'
import React from 'react'
// ... 

I ran babel compile the source code and I got an empty css object in compiled file

// ...
var css = {}
// ...

But if I change the source code to

import css from '../../assets/stylesheets/basic/loading.scss'  // use relative path
import React from 'react'
// ... 

Then I got the correct css object in compiled file

// compiled code
var css = {
  'loading-b': 'loading-b-fe5ceece94c6787b',
  'loadingB': 'loading-b-fe5ceece94c6787b'
};
// ...

Is there any way to make this plugin work with babel-plugin-module-resolver? Thank you.

camelCase option works differently from css-loader?camelCase

I use this babel plugin on server side, while using webpack css-loader on client side, to get css modules work in an isomorphic app.

I want to keep my classes in dashed style in css files, so I turn on the camelCase option on both side.
But they result in different class names.

This is my CSS:

// style.css
.bordered-box {
  border: 1px solid #ddd;
  min-height: 60px;
  padding: 1px 3px;
}

The server side result: <div class="style__borderedBox___1CfFu"></div>
The client side result: <div class="style__bordered-box___2hkXK"></div>

This is my babel plugin config:

["css-modules-transform", {
  "generateScopedName": "[name]__[local]___[hash:base64:5]",
  "extensions": [".css", ".less"],
  "camelCase": true,
  "preprocessCss": "./less-require-hook.js"
}]

And this is my webpack loaders config:

{
  test: /\.css$/,
  loaders: [
    "style-loader",
    "css-loader?modules&camelCase&localIdentName=[name]__[local]___[hash:base64:5]"
  ]
}

processCss file path

Thanks for cool project!

Though config seems straightforward i keep getting same output:

/Users/oleg/code/extreme/node_modules/babel-core/lib/transformation/file/index.js:591
      throw err;
      ^

Error: /Users/oleg/code/extreme/src/server-entry.js: Module '/Users/oleg/code/extreme/src/utils/runtimeStyles.js' does not exist or is not a function.
    at /Users/oleg/code/extreme/node_modules/babel-plugin-css-modules-transform/build/index.js:116:35
    at Array.forEach (native)
    at PluginPass.Program (/Users/oleg/code/extreme/node_modules/babel-plugin-css-modules-transform/build/index.js:77:32)
    at newFn (/Users/oleg/code/extreme/node_modules/babel-traverse/lib/visitors.js:310:19)
    at NodePath._call (/Users/oleg/code/extreme/node_modules/babel-traverse/lib/path/context.js:78:18)
    at NodePath.call (/Users/oleg/code/extreme/node_modules/babel-traverse/lib/path/context.js:49:17)
    at NodePath.visit (/Users/oleg/code/extreme/node_modules/babel-traverse/lib/path/context.js:108:12)
    at TraversalContext.visitQueue (/Users/oleg/code/extreme/node_modules/babel-traverse/lib/context.js:174:16)
    at TraversalContext.visitSingle (/Users/oleg/code/extreme/node_modules/babel-traverse/lib/context.js:124:19)
    at TraversalContext.visit (/Users/oleg/code/extreme/node_modules/babel-traverse/lib/context.js:219:19)

I swear to god i have the this file in proper directory with this content:

module.exports = function runtimeStyles(data, filename) {
  console.log(data, filename);
};

Babel config follows:

{
  "presets": ["es2015", "stage-0", "react"],
  "plugins": [
    ["css-modules-transform", {
      "processCss": "./src/utils/runtimeStyles.js"
    }],
    ["module-alias", [
      { "src": "./src/containers", "expose": "containers" },
      { "src": "./src/components", "expose": "components" },
      { "src": "./src/components/layouts", "expose": "layouts" },
      { "src": "./src/actions", "expose": "actions" },
      { "src": "./src/constants", "expose": "utils" },
      { "src": "./src/utils", "expose": "utils" }
    ]]
  ]
}

Any ideas what might cause this behaviour?

Updated css-modules-require-hook

Hello

A merge was made on the css-modules-require-hook. It fixed issues I'm having with scoped npm packages. So if you would like to bump the current version to 4.0.2 instead of 4.0.1 it would be fantastic

in package.json
"css-modules-require-hook": "^4.0.1",
to
"css-modules-require-hook": "^4.0.2",

Use plugin from webpack

I'm using this plugin from webpack and just wonder why you do not intended to use it on client side at all? What are possible implications of such use?

Sass support

I don't know why, but .sass not work πŸ€”

Generating empty css file

Plugin is generating an empty css file:

This is my configuration:

...
["css-modules-transform", {
  "extensions": [".css", ".scss", ".less"],
  "extractCss": "./dist/stylesheets/theme.css"
}],

I went through the source and my requires do get picked up and get transformed but it seems to fail here:

if (t.isExpressionStatement(path.parent)) {
  //buildClassNameToScope is working
  var p = path.replaceWith(buildClassNameToScopeNameMap(tokens));
  console.log(p)
  return p; // p = undefined :(
} else {
  path.remove();
}

Any idea what could be causing this?

Add better examples

IMHO it is very hard to understand how this works.

I think some real world examples with different combinations would help.

I looked into the tests but could not find any tests which combine certain properties (e.g. preprocessCss + generateScopedName)

As-is, I cannot use this plugin due to fear of misconfiguration.

Happy to contribute if I figure out how it works.

Prop `className` did not match.

Warning: Prop className did not match. Server: "Header__selected___3IRlm" Client: "Header__selected__3IRlm"

All classNames, rendered on the server has 3 undersores, but classNames, rendered on the client has 2.

Why is this plugin "intended only for backend compilation"?

In the docs, it says that this plugin "is intended only for backend compilation," but I see no reason why it can't be used for frontend compilation as well.

p.s. Sorry for asking a question in a GitHub issue (I know that's bad form). However, I believe it is an actual issue with the docs.

Example with PostCSS?

Hi, this plugin is really awesome and I'd love to use it to bundle a library.

The problem is that I don't seem to understand how to make this work with PostCSS? PostCSS by default has a promise based API. How can it work with preprocessCss option?

Also, is the async limitation just because you didn't have time to implement it or is it an actual limitation of the technology you used to create the plugin?

complexRequires and currentConfig problems with "prepend"

Hello!

It seems to be buggy when i define "prepend" configuration like :

["css-modules-transform", { "prepend": ["postcss-cssnext"] }]

https://github.com/michalkvasnicak/babel-plugin-css-modules-transform/blob/master/src/index.js#L30

Maybe you have to clone currentConfig otherwise you will overwrite all values during the rest of the process.

When we log the value of currentConfig, we can see the following output for the first file:

{ generateScopedName: '[name]__[local]___[hash:base64:5]',
  prepend: [ 'postcss-cssnext' ] }

Then we can see the following output for the second file:

{ generateScopedName: '[name]__[local]___[hash:base64:5]',
  prepend:
   [ Processor {
       version: '5.0.14',
       plugins: [Object],
       postcssPlugin: 'postcss-cssnext',
       postcssVersion: '5.0.14' } ] }

Finally we got the throwing message :

Configuration 'prepend' has to be valid path to a module at index 0 or it does not export a function.

Its weird that "prepend" has been updated no ?

Doesn't work as expected when programmatically calling babel

I'm making a custom build process that handles calling babel-core's transform itself for each file, each time with a custom extractCss property. This plugin looks like it's setting it's options only once instead of each time babel.transform is called so effectively the options passed to that call are actually irrelevant except for the 1st call.

Separately, there should be a way to print the css modules errors instead of just reporting nothing. It makes it difficult to debug css issues. I'd be willing to work on the PR but figured there could be a discussion first

Add option to ignore certain files

In my current app I have some files that have global css, which are just required, and they are even only required in the server (guarded by an if). It'd be useful to be able to avoid attempting to transform those cases, probably by supporting the ignore option in the same way the require hook allows.

What do you think?

extractCss.filename variables

[path] variable should contain only relative path without filename
[name] variable should contain only filename without extension

Global/Local CSS imports

Hi there,

I am having issues related to this PR in css-modules with this plugin:

css-modules/css-modules#65

I cannot import global (non module) scss files into my css modules files. Per that ticket I solved my server rendering by using webpack loaders, before I was using this library and babel.

I would still like to use this plugin for unit tests that may need to inline css module classnames into the components when running in enzyme. This plugin solves that need for me as long as I do not import global files into the non module css.

Example where it breaks:

@import "~client/styles/_vars.global.scss";

.nav {
  width: 96px;
  background-color: $blue;
}

Where $blue comes from the _vars.global.scss, and that file is not a module.

When using this library and a custom SCSS compiler, the SCSS compiler does not ever emit the result:

scssPreprocessor.js

const sass = require('node-sass');

module.exports = function processSass(data, filename) {
  console.log(data, filename);
  const result = sass.renderSync({
    data,
    file: filename
  }).css;
  console.log(result.toString('utf8'));
  return result.toString('utf8');
};

Where the second console never runs.

Do you have any ideas of what could solve this? Is there already a solution in the config?

Thanks,

Greg

How to add PostCSS ?

Seems like css-modules-require-hook has a use config that allows to pass a array of postcss plugins, but this doesnt seem to work here.

Any ideas?

Sometimes crashes

Changing nothing, sometimes this transform causes an exception to be thrown.

Successful run:

$ npm run build:html

> NODE_ENV=production node build.js

(node:26056) [DEP0013] DeprecationWarning: Calling an asynchronous function without callback is deprecated.

Failure:

$ npm run build:html

> NODE_ENV=production node build.js

/Users/.../Paper.css:1
(function (exports, require, module, __filename, __dirname) { .root {
                                                              ^

SyntaxError: Unexpected token .
    at createScript (vm.js:74:10)
    at Object.runInThisContext (vm.js:116:10)

Removing requirement for extension in import/composes

When using babel-plugin-css-modules-transform (which has saved my life, btw), you can write something like this:

// component.js
var styles = require('./styles'); // No extension

But this isn't possible:

// styles.css
.some-class {
  composes: another-class from './global'; /* No extension */
}

This is required, currently:

// styles.css
.some-class {
  composes: another-class from './global.css'; /* Extension */
}

Currently, webpack doesn't require the extension here and, to keep parity, it would make a lot of sense to not require it here either.

Error: provided an invalid property of "generateScopedName"

sorry if i've missed something but i'm getting the error when trying this
.bablerc

{
  "presets": ["es2015", "stage-0", "react"],
  "plugins": [
    "css-modules-transform", {
       "generateScopedName": "[name]__[local]___[hash:base64:5]"
    }
  ]
}

error

Error: Plugin 1 specified in "..../.babelrc" provided an invalid property of "generateScopedName"

it's working fine like this, but i need it to hash it like above.

{
  "presets": ["es2015", "stage-0", "react"],
  "plugins": [
    "css-modules-transform"
  ]
}

thanks.

Infinite loop when use composes for extract class from external file

Hi,
i have several problem when use composes from external file.
Try to explain the issue....

This is my configuration:

.babelrc

"css-modules-transform", {
  "preprocessCss": "./tools/preprocess/babel-scss.js",
  "generateScopedName": '[hash:base64:5]',
  "extensions": [".scss"]
}

babel-scss.js

module.exports = (data, file) => {

	try {
		
		return sass.renderSync({
			data,
			file
		}).css.toString('utf8');
	
	} catch (e) {
		
		console.error(e);
	
	}

};

module.scss

.header {
	composes: font-size-sm '../../styles/modules/_font-size.scss';
}

_font-size.scss

.font-size-sm  {
   font-size: 1rem;
}

This configuration generate an infinite loop:

C:\xampp\htdocs\react-redux-universal-hmr-boilerplate\src\components\Box\Box.scss
C:\xampp\htdocs\react-redux-universal-hmr-boilerplate\src\styles\modules\_font-size.scss
C:\xampp\htdocs\react-redux-universal-hmr-boilerplate\src\styles\modules\_font-size.scss
C:\xampp\htdocs\react-redux-universal-hmr-boilerplate\src\styles\modules\_font-size.scss
C:\xampp\htdocs\react-redux-universal-hmr-boilerplate\src\styles\modules\_font-size.scss
C:\xampp\htdocs\react-redux-universal-hmr-boilerplate\src\styles\modules\_font-size.scss
infinite loop.....
  • "babel-cli": "6.24.1",
  • "babel-core": "6.24.1",
  • "babel-loader": "7.0.0",
  • "babel-plugin-css-modules-transform": "1.2.7"

Any suggestions?
Thanks

Cannot read property 'keepImport' of undefined

happens when:

"plugins": ["css-modules-transform"]

vs.

"plugins": [
    ["css-modules-transform", {
      "keepImport": false
    }]
  ]
TypeError: src/button/index.js: Cannot read property 'keepImport' of undefined
    at PluginPass.ImportDefaultSpecifier (/Users/greada/Documents/workspace/s2/s2-component-library/node_modules/babel-plugin-css-modules-transform/build/index.js:194:43)
    at newFn (/Users/greada/Documents/workspace/s2/s2-component-library/node_modules/babel-traverse/lib/visitors.js:276:21)
    at NodePath._call (/Users/greada/Documents/workspace/s2/s2-component-library/node_modules/babel-traverse/lib/path/context.js:76:18)
    at NodePath.call (/Users/greada/Documents/workspace/s2/s2-component-library/node_modules/babel-traverse/lib/path/context.js:48:17)
    at NodePath.visit (/Users/greada/Documents/workspace/s2/s2-component-library/node_modules/babel-traverse/lib/path/context.js:105:12)
    at TraversalContext.visitQueue (/Users/greada/Documents/workspace/s2/s2-component-library/node_modules/babel-traverse/lib/context.js:150:16)
    at TraversalContext.visitMultiple (/Users/greada/Documents/workspace/s2/s2-component-library/node_modules/babel-traverse/lib/context.js:103:17)
    at TraversalContext.visit (/Users/greada/Documents/workspace/s2/s2-component-library/node_modules/babel-traverse/lib/context.js:190:19)
    at Function.traverse.node (/Users/greada/Documents/workspace/s2/s2-component-library/node_modules/babel-traverse/lib/index.js:114:17)
    at NodePath.visit (/Users/greada/Documents/workspace/s2/s2-component-library/node_modules/babel-traverse/lib/path/context.js:115:19)

Extensions with dot support

I have files with .module.less extension. But when I set extensions to this value, nothing happens. .less works.

`import './global.css'` does not work

Hello, I have two one issue.

First issue is while all these work...

import foo from './global.css' // even if not using foo
require('./global.css')

...this one doesn't work:

import './global.css'

It just gives the following error:

Module parse failed: global.css Unexpected token (1:0)
You may need an appropriate loader to handle this file type.

Second issue might not be related to this project but is confusing the hell out of me. In global.css I tried the following selectors to get some custom properties in:

:root {}
:global :root {}
:global(:root) {}

But none of those work, the whole block just gets ignored and doesn't end up in the bundle.

Interesting though is that I can use the custom properties in the global.css file, they are just replaced with their values... as I'm typing this I realize it might be CSSNext doing this intentionally πŸ˜…

Hope you can help me out, thanks in advance 😁

Related PR that introduced ES6 import support is #32 by @GabeMedrash.

Reliance on 'babel-plugin-transform-es2015-modules-commonjs'

Hi @michalkvasnicak--thanks for this great plugin. I've been using it for several months in various projects. In some of those projects I'm planning on transitioning to webpack v2, which can now parse es6 import and export statements (and so does not required 'babel-plugin-transform-es2015-modules-commonjs' to transpile, e.g., import into require(...) calls).

The final hurdle in that transition is to have my import styles from './style.css' statements be properly processed by this plugin without having to transform them into, e.g., var styles = require('./style.css') first.

I have a PR ready for your review that would extend this plugin to be able to run the transform without having a dependency on 'babel-plugin-transform-es2015-modules-commonjs'. Is this something you would consider?

Inject styles into head tag like style-loader

I apologize if this is not the correct repository to post into. I have been using css modules with style-loader in a project for some time, and it builds a <style> block in my <head> tags (instead of bundling everything into an external file using extract-text-webpack-plugin). I am trying to turn my project into a private library that I can install in my other projects from a private git server. Doing so led me here. When I use this project I can see that it successfully generates the hashed class names for my elements. However, I lose the generated <style> block in my document so the class names are virtually meaningless.

I am new to package development so maybe I am going about this the wrong way, but is there a way for this project to emulate the behavior of style-loader and add the hashed css files inside of a <style> tag on the page? I am currently not using any config options with this project, just adding "plugins": ["css-modules-transform"] to my .babelrc. Any pointers at all would be helpful. Thank you!

importing from node_modules '~' path

using @import '~my-module/css/file' gives me an error on the server side but works fine on my frontend with webpack.

error:

Error: File to import not found or unreadable: ~@my-module/css/file.

When I switch to @import './node_modules/my-module/css/file' it works fine.

Keep the require('./styles.css') in the JS file

Right now this plugin transforms

// MyComponent.js
import styles from './MyComponent.css';
// ...

into

// MyComponent.js
var styles = {
  'layout': 'page__layout___2xRof'
};
// ...

I also configured the extractCss option to put the CSS output file right next to the babelified JS output file of each component. However, would it be possible to append a require('./MyComponent.css) at the beginning of the output JS? I.e. to something like:

// MyComponent.js
require('./MyComponent.css');
var styles = {
  'layout': 'page__layout___2xRof'
};
// ...

cannot use "generateScopedName" + "preprocessCss"

When I set both only one works (preprocessCss)

when I disable preprocessCss, generateScopedName works

"plugins": [
    [
      "css-modules-transform", {
        "generateScopedName": "./scripts/generate-scoped-name.js",
        "preprocessCss": "./scripts/preprocess-css.js",
        "extensions": [".css", ".scss"],
      }
   ]
]

Not sure if I am doing something wrong

generate-scoped-name.js (never called if preprocessCSS is set)

module.exports = function generateScopedName (name, file, code) {
  console.log('I work! (name)')
}

preprocess-css.js

module.exports = function preprocessCSS (data, filename) {
  console.log('I work! (process)')
}

Use cmhr.js (if exists)

It'd be nice if you could configure css-modules-require-hook via the cmrh.js config file. I have a use-case where I need to use a postCSS plugin with options set:
postcss.config.js:

const variables = require('./src/brand/variables');

module.exports = {
  plugins: [
    require('postcss-custom-properties')({ variables }),
  ],
};

.babelrc

"plugins": [
  [
    "css-modules-transform",
    {
      "prepend": ["how-do-I-use-my-dynamic-plugin"],
      "generateScopedName": "[name]__[local]___[hash:base64:5]",
      "extensions": [".css"],
      "extractCss": "./dist/app.css"
    }
  ]
]

I can't do "prepend": [require('postcss-custom-properties')({ variables })] because .babelrc isn't a js file. If this plugin read from cmrh.js (if it exists) problem would be solved.

The camelCase option needs to support string values

Hi,

Thanks for this lib, we're heavily using it in our project.

Regarding the camelCase option, setting it to true causes a lot of duplications since original class names are kept, e.g.:

var Styles = {
  'link': 'link-modules__link___3oOIo',
  'linkInGroup': 'link-modules__link-in-group___2fh2a',
  'linkInLinks': 'link-modules__link-in-links___3IT7k',
  'linkDisabled': 'link-modules__link-disabled___2qbP8',
  'link-in-group': 'link-modules__link-in-group___2fh2a',
  'link-in-links': 'link-modules__link-in-links___3IT7k',
  'link-disabled': 'link-modules__link-disabled___2qbP8'
};

In order to solve this, css-modules-require-hook has just supported new string values: only|dashOnly per css-modules/css-modules-require-hook#89 , and released in v4.0.6 https://github.com/css-modules/css-modules-require-hook/releases/tag/4.0.6

camelCase: true|'dashes'|'dashesOnly'|'only'

In latest babel-plugin-css-modules-transform, I found that it limits camelCase to be a boolean:

Error: Configuration 'camelCase' is not a boolean
    at Object.camelCase (.../node_modules/babel-plugin-css-modules-transform/build/options_resolvers/camelCase.js:18:15)

Is it possible to support the new values ('dashes'|'dashesOnly'|'only')?

Thanks.

Is there a way to properly compile the source code using this plugin

The plugin seems to work only during runtime. for example , i can run it fine when i use the below

"start": "nodemon server/server.js --exec babel-node --plugins css-modules-transform",

however , when i try to compile the entire directory using babel-cli.

"build": "babel server -d serverLib --plugins css-modules-transform"

i still get the css error. Is there anyway i can make it to work on the compiled version as well?

user less @import something error

{ [Error: '../style/Theme.less' wasn't found. Tried - ../style/Theme.less,../style/Theme.less]
type: 'File',
filename: 'input',
index: 0,
line: 1,
callLine: NaN,
callExtract: undefined,
column: 0,
extract: [ undefined, '@import "../style/Theme.less";', '' ],
message: ''../style/Theme.less' wasn't found. Tried - ../style/Theme.less,../style/Theme.less',
stack: undefined }

// processLess
const less = require('less');

module.exports = function processLess(data) {
let css;
less.render(data, { sync: true }, (e, output) => {

css = output.css;

});
return css;
};

extractCss wipes out css file

// "babel-plugin-css-modules-transform": "^1.2.7",
// .babelrc
{
  "presets": [
    "es2015",
    "react"
  ],
  "plugins": [
    "transform-runtime",
    "transform-decorators-legacy",
    "transform-class-properties",
    "babel-plugin-transform-object-rest-spread",
    [
      "css-modules-transform",
      {
        "camelCase": true,
        "extractCss": "node_modules/flexboxgrid/dist/flexboxgrid.css"
      }
    ]
  ]
}

when I run my build command I am noticing the file node_modules/flexboxgrid/dist/flexboxgrid.css is mutated into an empty file - is there a way to build using this plugin in a way that is destructive?

babel-plugin-transform-postcss

Hi @michalkvasnicak,

I just wanted to bring your attention to babel-plugin-transform-postcss which I based off of the awesome work that you've done here.

This plugin wasn't quite fitting with what I wanted, so I started from what you had & went in a slightly different direction. The main differences are:

  • Doesn't use the require hook to run PostCSS
  • Supports asynchronous PostCSS plugins
  • Uses postcss-load-config (which appears to be a future standard) to locate postcss.conf.js

I still have a few things left that I want to address in the build system that uses it (namely watch support via Browserify which seems similar to #27 here). [edit] wbyoung/babel-plugin-transform-postcss@0e655ff

Error with Babel 6.24.0

When used with Babel 6.24.0, I get the following error. I shortened the absolute path to ./node_modules. Looking at the Babel source, it looks like manipulateOptions was only added in Babel 7.

ReferenceError: [BABEL] src/foo/foo.js: Unknown option: ./node_modules/babel-plugin-css-modules-transform/build/index.js.manipulateOptions. Check out http://babeljs.io/docs/usage/options/ for more information about options.

I'musing the following custom preset to configure babel-plugin-css-modules-transform.

module.exports = {
    plugins: [
        [require('babel-plugin-css-modules-transform'), {
            extractCss: {
                dir: 'lib',
                filename: '[path]/[name].css',
            },
        }],
    ],
};

`/**` comments incorrectly built

Not sure where in the pipeline this is occurring but this is getting outputted in the .css

 {
  /**
 * React Select
 * ============
 * Created by Jed Watson and Joss Mackison for KeystoneJS, http://www.keystonejs.com/
 * https://twitter.com/jedwatson https://twitter.com/jossmackison https://twitter.com/keystonejs
 * MIT License: https://github.com/JedWatson/react-select
*/ }

My preprocessCss script looks like:

const sass = require('node-sass');
const postcss = require('postcss');
const autoprefixer = require('autoprefixer');

module.exports = function processSass(data, filename) {
    let result;
    result = sass.renderSync({
        data: data,
        file: filename
    }).css;
    result = postcss([autoprefixer]).process(result).css;
    return result.toString('utf8');
};

I've tried adding outputStyle: 'compressed' to sass.renderSync but that didn't change the output

Unknown arguments: processOpts

According to the css-modules-require-hook docs, processOpts is not a valid option. Should this be processorOpts instead? I receive this error with the former option.

const scssParser = require('postcss-scss').parse;

require('babel-register')({
    ignore: /node_modules(?=(.(?!\.(scss|css)$))*$)//,
    plugins: [
        ['css-modules-transform', {
            extensions: ['.css', '.scss'],
            processOpts: { parser: scssParser },
        }],
    ],
});

screen shot 2017-02-15 at 4 19 58 pm

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.