jeremy.mooer
jeremy.mooer

Reputation: 645

What are the best practices on creating a css-only javascript library/bundle

I would like to create a library that can be npm installed into one of a dozen javascript projects (some are ES6 projects, but many are much older ES5 projects). The library project also has a few very common javascript methods / classes / components / etc.

(As an aside, the library project includes a couple of common methods and utilities that were written ES6, but transpiled with webpack+babel to also be used in both ES5 and ES6 projects. Meaning: my input file in webpack.config is a file of module.exports; my output is a single build file.)

The main issue:

On implementation on ES6, a react project for example, I'm not sure how to import 'nodeModuleName/someSimpleCssFile' that will allow the webpack/babel (on the implementation side) to do it's thing. On one project in particular, the only thing being imported from this project is a single global stylesheet.

On implementation on the older projects, the developer needs to be able to use the <link /> tag to pull in one style sheet.

I know I could simply put all of the css files in a folder that is designated in the main property of package.json, but is this the best way? It also seems like, going forward, if the styler added background: url('some/path/to/image.png'); that using the babel transpiler would pull all of that stuff into the single build file.

The question in that case would be, how do I import only one css file that is being transpiled into a single build file? Or, rather, how do I even include that single css file in my main module.exports to be exported so that I can, somehow, import only that css file into an ES6/ES2015 project?

Upvotes: 0

Views: 159

Answers (1)

Brian Peacock
Brian Peacock

Reputation: 1849

A way of achieving this might be to store your CSS style info in an Object within your library and dynamically create and populate a <style> tag when the page loads.

/* example */
var someStyles = {
    body: {
        color: '#fff',
        'background-color': '#000',
        'font-family': 'sans-serif',
        margin: '33px'
    },
    'h1, h2, h3, h4': {
        'font-weight': 'normal'
    },
    ID_box: {
        width: '100%',
        height: 'auto',
        color: '#000',
        'background-color': '#fff'
    },
    CLASS_cell: {
        border: '1px solid #999',
        padding: '5px 10px'
    }
};

var sTag = document.createElement('style');
var css = '';

sTag.type = 'text/css';
sTag.scoped = 'true';

Object.keys(someStyles).forEach(function(s) {
    var rules = someStyles[s];

    css += s.replace(/ID_/g, '#').replace(/CLASS_/g, '.') + ' {\n';

    Object.keys(rules).forEach(function(r) {
        css += '  '+ r + ': ' + rules[r] + ';\n';
    });

    css += '}\n';
});


sTag.textContent = css;

document.body.insertBefore(sTag, document.body.firstChild);

Just a thought :)

Upvotes: 1

Related Questions