stephenlacy / gulp-stylus

Stylus plugin for gulp
MIT License
223 stars 60 forks source link

Stylus inside style tags? #191

Closed gavinmcfarland closed 2 years ago

gavinmcfarland commented 7 years ago

Hi there.

Is there a way I can use gulp-stylus to process a html file with style tags?

stephenlacy commented 7 years ago

This only passes the input files to stylus. The only way I have seen is to process the html, such as: https://stackoverflow.com/questions/12272936/is-it-possible-to-use-stylus-plugins-with-inline-stylus-code-embedded-in-a-jade The official response: https://github.com/pugjs/pug/issues/760

Now.... this is what I would do: Create a simple parser for getting all the <style>

const rgx = /<style*>([^<>]+)<\/style>/
const input = '<style> body background: white </style>'
input.match(rgx)[1]
// => ' body background: white '

Then I'd run stylus over it and inject the css back into the style tags.

More complete example:

const stylus = require('stylus')
const rgx = /(<style*>)([^<>]+)(<\/style>)/

const input = '<head> <style> body { background: white } </style> </head>'

const matches = rgx.exec(input)

const before = input.substr(0, matches.index)
const after = input.substr(matches.index + matches[0].length)
const prefix = matches[1]
const source = matches[2]
const suffix = matches[3]

stylus.render(source, (err, css) => {
  console.log(before + prefix + '\n' + css + suffix + after)
})

output:

<head> <style>
body {
  background: #fff;
}
</style> </head>
gavinmcfarland commented 7 years ago

Thanks. That was very generous of you to take the effort to explain how I might be achieve this! I'm going to give it a go.

I'm using web components so being able to do this will be a real life saver, as at the moment I'm having to manually process the stylus files and copy them into the html file. 😄