vuejs / vueify

Browserify transform for single-file Vue components
MIT License
1.17k stars 152 forks source link

Inline @import in plain CSS #219

Open inca opened 6 years ago

inca commented 6 years ago

Hey everyone,

I was looking for a simple enough way to work with some basic external stylesheets, but as mentioned in #149 there is no CSS inlining supported out of box.

Of course I was able to achieve what I want by installing postcss-import to the regular PostCSS chain — but this way imported files do not get tracked by compiler (which means, no hot reloading, not even recompiling when stuff changes). So it's not really feasible to develop this way.

Upon briefly inspecting vueify's sources I found that tracking a dependency is simply a matter of emitting the dependency event on compiler, so I came up with this solution:

    customCompilers: {
        css(content, cb, compiler) {
            const resolve = (id, basedir) => {
                const file = path.resolve(basedir, id);
                compiler.emit('dependency', file);
                return file;
            };
            postcss()
                .use(atImport({ resolve }))
                .process(content, {
                    // this could point to a different location,
                    // depends on where you'd like to resolve @imports from
                    from: path.resolve(__dirname, 'package.json'),
                })
                .then(result => {
                    // console.log(result);
                    cb(null, result.css);
                }, err => cb(err));
        },
    },

The drawbacks are:

Any suggestions/ideas are welcome! TIA