질문
CSS 파일의 스타일로 헤드 script 태그를 만들어야합니다. styles / style.css
를 문자열로 구문 분석하여 documentStyles
변수를 채우려면 어떻게해야합니까? 이것은 Node.js 함수에서 발생합니다.
style.css
p {
text-align: center;
}
index.js
const documentStyles = // SOMETHING TO STRINGIFY style.css
const document = `
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<style>
${documentStyles}
</style>
</head>
<body>
<p>Here's the test</p>
</body>
</html>
`
답변1
NodeJS fs.readFileSync
.
const fs = require('fs');
try {
const documentStyles = fs.readFileSync('styles/style.css');
const document = `
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<style>
${documentStyles}
</style>
</head>
<body>
<p>Here's the test</p>
</body>
</html>
`;
} catch(e) {
console.log('Error:', e.stack);
}
답변2
Christos Lytras가 지적했듯이 파일 시스템 (fs) 모듈을 통해 노드에서 파일의 문자열 내용을 얻는 것은 매우 쉽습니다.하지만 JavaScript가 API를 통해 작업 할 수있는 객체를 얻는 방법이 걱정된다면 아마도 CSSStyleSheet API 가 필요합니다.
이 개체에는 cssRule 개체. 이를 반복하고 type
속성을 확인합니다 (다른 규칙 유형은 내부 구조가 다르기 때문).
대부분의 경우 유형 : 1
이 있습니다. 즉 cssStyleRule 객체 :
- a
selector
property (like .my-awesome-class
), and
- a
style
property (like { font-size: 1.5em; color: hotpink; }
).
이 수준에 도달하면 모두 매우 간단하지 않은 경우 정규식으로 선택기와 스타일을 구문 분석해야 할 수 있습니다 . documentStyles
변수에 할당 할 사용자 지정 개체를 빌드합니다.
무엇보다도 CSS의 kebab-case
이름을 JavaScript의 camelCase
형식으로 변환 하고 싶을 것입니다 (또는 줄에서 코드를 찾을 수 있습니다. 당신을 위해 해.)
(이 질문 에 대한 답변 특정 규칙을 찾고 스타일 속성을 검사하기 위해 스타일 시트를 파헤치는 예제를 제공합니다.)
출처 : https://stackoverflow.com/questions/62685046/convert-css-file-to-string-in-javascript-node-js