3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

ちょちょっと手元でSCSSを書きたい時のマクロ

Last updated at Posted at 2025-05-08

DOMパーサーを利用してネストだけ解釈します。

testcss.html

class SCSS{
	compile(css){
		var s = ''
		var r = css
		while(r!=s){
			s = r
			var r = s.replace(/([^;{}<>]+){([^{}]*)}/g,(m,k,v)=>{
				return `<n key="${k.trim()}">${v.trim()}</n>`
			})
		}
		var n = new DOMParser().parseFromString(`<xml>${s}</xml>`,'text/xml').firstChild
		var a = Array(...n.querySelectorAll('n')).map(n=>{
			var b = [[],n]
			while(n.nodeName=='n'){
				b[0].unshift(n.getAttribute('key'))
				n = n.parentNode
			}
			return b
		})
		return a.map(b=>{
			Array(...b[1].children).forEach(n=>n.remove())
			var s = b[1].textContent.replace(/;\s+/g,';').replace(/:\s+/g,':')
			if(s) return `${b[0].join(' ')}{${s}}`
		}).filter(Boolean).join("\n")
	}	
}

/*
out:
#test{font-size:2em;}
#test UL{line-height:1.5;font-size:3em;}
#test UL LI.sss{font-size:50vw;}
#test2{font-size:3em;}
#test2 UL{line-height:1.5;font-size:3em;}
#test2 UL LI.sss{font-size:50vw;}
*/

console.log(new SCSS().compile(`
	#test {
		font-size:2em;
		UL {
			line-height:1.5;
			LI.test	{}
			LI.sss	{font-size:50vw;}
			font-size:3em;
		}
	}
	#test2 {
		font-size:3em;
		UL {
			line-height:1.5;
			LI.test	{}
			LI.sss	{font-size:50vw;}
			font-size:3em;
		}
	}
`))

3
1
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?