vuejs/vueify

Inline @import in plain CSS

inca opened this issue · 0 comments

inca commented

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:

  • it's more than 10 lines, so it deserves a separate library — could be much less hassle if this was implemented in vueify natively, but this would mean +1 dependency
  • it bypasses the vueify's native PostCSS chain, so stylesheets are (probably) parsed twice — could be much less pain if compiler instance was somehow available when defining/instantiating postcss plugins

Any suggestions/ideas are welcome! TIA