npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

babel-plugin-css-to-js-transform

v1.0.2

Published

The transform generate a [filename]_css.js file from [filename].css. It inserts classNames by css-modules, and insert a _getCss function. It is keeps the require or import in the file, only replaces the file name with the new file name.

Downloads

30

Readme

Babel-plugin-css-to-js-transform

This Babel plugin finds all require and all import function for css files, and replace them with a new file with this name [filename]_css.js. It is keeps the the require and the import. In the file only replaces the file name with the new file name.

Then the transform generate a new file [filename]_css.js from [filename].css. It inserts class names as default export by css-modules with css-modules-require-hook package, and insert a getter _getCss function to the default object like some style loaders eg: isomorphic-style-loader

This plugin is based on the fantastic babel-plugin-css-modules-transform.

Why?

There are two reasons what the plugin was written:

  1. The exists plugins don't support async plugins for postcss
  2. Doesn't want insert class names to the file because it causes many duplicates and increases the bundle size.

These are especially interesting if you want to create a reusable high order component or module, and you want to add a css. When you create an end user type software use webpack and style-loaders.

Warning

This plugin is experimental, pull requests are welcome.

Example

/* srcDir/test_require.css */

.someClass {
    color: red;
    display: flex;
}
// srcDir/component.js
const styles = require("./test_import.css");
// outDir/test_require_css.js
"use strict";

Object.defineProperty(exports, "__esModule", {
    value: true
});

const tokens = {
    "someClass":"test_require_31cRH"
}; 

tokens._getCss = function () {
    return `/* imported from test_require.css */ .test_require_31cRH { color: red; display: flex; } `;
};

exports["default"] = tokens;
// outDir/component.js
var styles = require("dir/test_require_css.js")["default"];

Installation

npm install --save-dev babel-plugin-css-to-js-transform

Include plugin in .babelrc

{
    "plugins": ["css-to-js-transform"]
}

With custom options

module.exports = function (api, opts, env) {
    return {
        "plugins": [
            [
                require("babel-plugin-css-to-js-transform").default,
                {
                    cssModulesOptions: {
                        generateScopedName: "[name]_[hash:base64:5]",
                        //more options here: [css-modules-require-hook](https://github.com/css-modules/css-modules-require-hook)
                    },
                    alias: function alias({filePathOrModuleName, root, outDir, srcDir}) {
                        let relativeFromRoot = relative(root, filePathOrModuleName);
                        //if the processed css is exists the plugin read it from out folder.
                        if (relativeFromRoot.slice(0,3) === srcDir && existsSync(resolve(root, outDir + relativeFromRoot.slice(3)))){
                            relativeFromRoot = outDir + relativeFromRoot.slice(3)
                        }
                        return resolve(root, relativeFromRoot);
                    },
                    outDir: "dist"
                }
            ]
        ]
    }
}

Using a processor

When using this plugin with a processor, run it before this plugin running. This example show you how create a build function with postcss.

You can try it in test package from command line: babel-plugin-test build

// tools/build.js
const postcss = require("postcss");
const path = require("path");
const fs = require("fs");

/*...*/

/**Create a postcss runner*/
async function processCssFunction(processCss) {
    const plugins = [
        require("postcss-import")(),
        require("postcss-calc")(),
        require("pleeease-filters")(),
        require("pixrem")(),
        require("postcss-flexbugs-fixes")(),
        require("postcss-preset-env")({
            stage: 3,
            autoprefixer: { flexbox: "no-2009" },
        }),
    ];
    const runner = postcss(plugins)
    return await processCss({postcss, plugins, runner});
}

/**Create the processCss function what find all css files in src folder,
 * and it create generated css files to dist folder.
 * You can set up root, src and dist folders
 */

async function processCss(p = {}) {

    const {rootPath, distPath, srcPath} = getPaths(p)

    await processCssFunction(async function processCss({runner}) {

        function recursiveReadDir(entriesPath, o = {}) {
            fs.readdirSync(entriesPath).forEach(function(file){
                const curPath = path.resolve(entriesPath, file);
                if(fs.lstatSync(curPath).isDirectory()) {
                    recursiveReadDir(curPath, o);
                } else if (file.match(".css")){
                    const srcRelative = path.relative(srcPath, curPath);
                    const rootRelative = path.relative(rootPath, curPath);
                    o[srcRelative] = "./"+rootRelative;
                }
            });
        }

        const entries = {};
        recursiveReadDir(srcPath, entries);

        await Promise.all(Object.keys(entries).map(async function (relativePath) {
            return new Promise(async function(resolve, reject) {
                try {
                    const from = path.resolve(srcPath, relativePath);
                    const to = path.resolve(distPath, relativePath);
                    const css = fs.readFileSync(from);
                    const result = await runner.process(css, {from: from, to: to})
                    if (!fs.existsSync(path.dirname(to))){
                        fs.mkdirSync(path.dirname(to), { recursive: true });
                    }
                    if (!fs.existsSync(to)) {
                        fs.writeFileSync(to, result.css, function () {
                            return true;
                        })
                        console.log("Css processed: " + to)
                    } else {
                        console.log("File aready exists, run clean script or delete it manually before process css: " + to)
                    }
                    return resolve();
                } catch (e) {
                    return reject(e)
                }
            })
        }))

    })
}

/*...*/

/**
 * Build: first processCss, then babel
 **/
async function build(p = {}) {

    const {rootPath, distPath, srcPath} = getPaths(p)

    await clean(p);
    await processCss(p);
    const exec = require("child_process").exec;
    const execText = path.resolve(rootPath, "node_modules/.bin/babel") + " " + srcPath + " --presets=babel-preset-for-test --out-dir " + distPath;
    console.log("Run babel: " + execText);
    await exec(execText).stderr.pipe(process.stderr);
}

/*...*/

License

MIT