CSS-in-JS 란?

CSS-in-JS는 단어 그대로 자바스크립트 코드에서 CSS를 작성하는 방식을 말합니다. 2014년 페이스북 개발자인 Christopher Chedeau aka Vjeux가 처음 소개하였습니다.

 

Vjeux는 CSS를 작성하는 어려움을 다음과 같이 설명하였으며 CSS-in-JS로 이들 이슈를 모두 해결할 수 있다고 강조했습니다.
- Global namespace: 글로벌 공간에 선언된 이름의 명명 규칙 필요
- Dependencies: CSS간의 의존 관계를 관리
- Dead Code Elimination: 미사용 코드 검출
- Minification: 클래스 이름의 최소화
- Sharing Constants: JS와 CSS의 상태 공유
- Non-deterministic Resolution: CSS 로드 우선 순위 이슈
- Isolation: CSS와 JS의 상속에 따른 격리 필요 이슈

그리고 기존 CSS 관리의 어려움을 해결한 페이스북의 사례를 소개하였습니다. 이후 개념이 발전하면서 많은 라이브러리가 등장했습니다.

 

 

CSS-in-JS 사용률 - 출처 : https://2021.stateofcss.com/en-US/technologies/css-in-js

이 중 가장 대표적인 CSS-in-JS 라이브러리인 Styled Components를 살펴보겠습니다. Styled Components는 CSS-in-JS 스타일링을 위한 프레임워크입니다. 자바스크립트의 태그가 지정된 템플릿 리터럴과 CSS의 기능을 사용하여 구성 요소에 반응하는 스타일을 제공합니다. 장점은 다음과 같습니다. - CSS 모델을 문서 레벨이 아닌 컴포넌트 레벨로 추상화하는 모듈성 - CSS-in-JS는 JavaScript 환경을 최대한 활용 - 자바스크립트와 CSS 사이의 상수와 함수를 공유 - 현재 사용 중인 스타일만 DOM에 포함 - 짧은 길이의 유니크 한 클래스를 자동으로 생성하는 코드 경량화 단점으로는 러닝 커브(Learning Curve), 새로운 의존성 발생, 별도의 라이브러리 설치에 따른 번들 크기 증대 및 CSS-in-CSS에 비해 느린 속도 등을 들 수 있습니다. Styled Components는 스타일링을 위한 코드 사용량이 줄어들고 CSS 문법에 친화적입니다. 이는 아래 예시를 보면 알 수 있습니다.

 

 

CSS-in-CSS vs CSS-in-JS

앞서 CSS-in-CSS와 CSS-in-JS를 간단히 살펴보았지만 어떤 방식이 더 낫다고 쉽게 말할 수는 없습니다.

다만 본인의 경험에 비추어 봤을 때 작업자의 성향이나 판단이 필요한 부분이나 개발 효율성에 중점을 둔 컴포넌트 위주의 프로젝트라면 CSS-in-JS를 고려하는 것이 좋습니다. 필요한 컴포넌트 페이지의 CSS 스타일 요소만 로딩하기 때문입니다.

반면 사용자 편의에 방점을 둔 인터렉티브한 웹 프로젝트라면 랜더링 시 모든 CSS 스타일 요소를 로딩하는 CSS-in-CSS 방식을 권장하는 바입니다.

 

CSS-in-JS 장점

  • 컴포넌트로 생각하기— 더이상 스타일시트의 묶음을 유지보수 할 필요가 없습니다. CSS-in-JS는 CSS 모델을 문서 레벨이 아니라 컴포넌트 레벨로 추상화합니다(모듈성).
  • CSS-in-JS는 JavaScript 환경을 최대한 활용하여 CSS를 향상시킵니다.
  • "진정한 분리 법칙"—스코프가 있는 선택자로는 충분하지 않습니다. CSS에는 명시적으로 정의 하지 않은 경우, 부모 요소에서 자동으로 상속되는 속성이 있습니다. jss-isolate 플러그인 덕분에 JSS 규칙은 부모 요소의 속성을 상속하지 않습니다.
  • 스코프가 있는 선택자—CSS는 하나의 전역 네임스페이스만 있습니다. 복잡한 애플리케이션 내에서 선택자 충돌을 피할 수 없습니다. BEM과 같은 네이밍 컨벤션은 한 프로젝트 내에서는 도움이 되지만, 서드파티 코드를 통합할 때는 도움이 되지 않습니다. JSS는 JSON으로 표현된 것을 CSS로 컴파일 할 때, 기본적으로 고유한 이름을 생성합니다.
  • 벤더 프리픽스—생성된 CSS 규칙은 자동적으로 벤더 프리픽스가 붙어있으므로 생각할 필요가 없습니다.
  • 코드 공유—JavaScript와 CSS사이에 상수와 함수를 쉽게 공유할 수 있습니다.
  • 현재 화면에 사용중인 스타일만 DOM에 있습니다(react-jss).
  • 죽은 코드 제거
  • CSS 유닛 테스트!

 

CSS-in-JS 단점

  • 학습 곡선(Learning curve)
  • 새로운 의존성
  • 신규 팀원이 코드베이스에 적응하기 어렵게 만듭니다. 프론트엔드를 처음 접하는 사람들은 "더" 많은 것을 배워야합니다.
  • 현상 유지를 위한 도전 (꼭 단점은 아니다.)

 

원문참조 

- https://www.samsungsds.com/kr/insights/web_component.html           

- https://d0gf00t.tistory.com/22

 

반응형

 

 

https://www.surfit.io/tag/%EB%94%94%EC%9E%90%EC%9D%B8%20%EC%8B%9C%EC%8A%A4%ED%85%9C

 

#디자인 시스템 콘텐츠 - 서핏

새 탭에서 펼쳐지는 맞춤 커리어 콘텐츠. 매일 성장하고 더 멋지게 일하세요!

www.surfit.io

 

반응형

'UXUI Development > Design System' 카테고리의 다른 글

디자인시스템  (0) 2022.04.21

디자인 시스템 관리 및 유지를 위한 도구

  • 인비전 DSM(Invision DSM)
  • 피그마(Figma)
  • 액슈어(Axure)
  • 스케치(Sketch)
  • 어도비 XD(Adobe XD)
  • 제로헤이트(ZeroHeight)

 

디자인시스템 적용 예

https://developer.apple.com/design/resources/

 

Apple Design Resources

Design apps quickly by using Sketch and Photoshop templates, plug-ins, and preconfigured UI elements.

developer.apple.com

https://developer.samsung.com/design-system

 

Design System - Design | Samsung Developers

The world runs on you.

developer.samsung.com

https://developer.samsung.com/one-ui/index.html

 

https://karrisaarinen.com/posts/building-airbnb-design-system/

 

Creating the Airbnb Design System

Working in software development and design, we are often required to ship one-off solutions. Sometimes we’re working within time constraints and sometimes we just haven’t yet agreed upon a path forward. These one-off solutions aren’t inherently bad,

karrisaarinen.com

 

https://www.audi.com/ci/en/guides/user-interface/introduction.html

 

UI Introduction

Animations All animations have the dynamic character defined in the look, giving an application a lively feel. They perform functional tasks in the interface and improve the user experience: they guide the user through an application, help provide visual o

www.audi.com

 

https://baseweb.design/components/

 

https://baseweb.design/components/

 

baseweb.design

 

https://www.carbondesignsystem.com/

 

Carbon Design System

Carbon is IBM’s open source design system for products and digital experiences. With the IBM Design Language as its foundation, the system consists of working code, design tools and resources, human interface guidelines, and a vibrant community of contri

www.carbondesignsystem.com

 

https://design.socar.kr/

 

쏘카 브랜드 디자인 가이드

 

design.socar.kr

 

http://styleguide.co.kr/index.php

 

https://websrepublic.co.kr/bbs/board.php?bo_table=news&wr_id=418 

 

(주)웹스리퍼블릭

반응형웹사이트 제작전문 웹스리퍼블릭,15년 경력 전문 웹에이전시, 반응형웹, 모바일웹, 쇼핑몰 제작

websrepublic.co.kr

 

반응형

'UXUI Development > Design System' 카테고리의 다른 글

디자인시스템 2  (0) 2022.04.21

Vue에서 PDF파일 보기, 다운로드, 프린트 기능 지원하기

Install vue-pdf-app

npm i vue-pdf-app

 

Pdf.vue

// Pdf.vue
<template>
    <VuePdfApp pdf="./../resume_kangjiyeon.pdf" page-scale="100" @open="openHandler"></VuePdfApp>
</template>
<script>
import VuePdfApp from "vue-pdf-app";
export default {
  components: {
    VuePdfApp,
  },
  methods: {
    openHandler(pdfApp) {
      window._pdfApp = pdfApp;
    },
  },
};
</script>
<style scoped>
@import "https://unpkg.com/vue-pdf-app@2.0.0/dist/icons/main.css";
</style>

 

https://www.npmjs.com/package/vue-pdf-app

 

vue-pdf-app

Vue 2 pdf viewer. Latest version: 2.1.0, last published: 10 months ago. Start using vue-pdf-app in your project by running `npm i vue-pdf-app`. There are 2 other projects in the npm registry using vue-pdf-app.

www.npmjs.com


 

https://codesandbox.io/s/mqyzy8158x?file=/src/App.vue 

 

Vue PDF Download - CodeSandbox

Vue PDF Download by sakapun using html2canvas, pdfmake, vue

codesandbox.io

https://codesandbox.io/s/vue-pdf-app-external-pdfj-interaction-g5jeb?file=/src/App.vue 

 

vue-pdf-app-external-pdfj-interaction - CodeSandbox

[Vue warn]: Invalid prop: type check failed for prop "field"

codesandbox.io

https://github.com/sandanat/vue-pdf-app

 

반응형


https://ui.toast.com/weekly-pick/ko_20190430

 

앱 테마 구현 - Vue.js와 스타일드 컴포넌트로 실시간 테마 구현하기

Vue.js 프로젝트를 진행하면서 구현하기 조금 까다로웠던 기능이 있다. 완벽한 Vue 문서(Docs)만으로 바로 답을 찾을 수 없었던 부분이 있었는데, 고객 요구 사항으로 사용자 프로필에 대한 테마를

ui.toast.com

 

반응형

Typeit

https://www.typeitjs.com/

 

TypeIt

The most versatile JavaScript typewriter effect library on the planet.

www.typeitjs.com

 

Scrollout

https://scroll-out.github.io/

 

ScrollOut

Effects and CSS Vars on Scroll!

scroll-out.github.io

 

anime.js

css속성, css transform, SVG와  DOM요소의 속성, Javascript객체를 사용하여 동작하는 Javascript 애니메이션 라이브러리. 

설치 및 Import

npm install animejs --save
import anime from 'animejs/lib/anime.es.js';
<template>
  <div class="container">
  	<p class="target">target anime</p>
  </div>
</template>

export default {
	mounted() {
      this.$anime({
        targets: '.target',
        translateX: '50px',
        duration: 3000
      })
   	}
}

 

https://github.com/juliangarnier/anime

 

GitHub - juliangarnier/anime: JavaScript animation engine

JavaScript animation engine. Contribute to juliangarnier/anime development by creating an account on GitHub.

github.com


GSAP

GreenSock에서 만든 자바스크립트 애니메이션 라이브러리로 

복잡한 애니메이션을 구현하기위한 도구. 

https://greensock.com/gsap/

 

GSAP

Timeline Tip: Understanding the Position Parameter The secret to building gorgeous sequences with precise timing is understanding the super-flexible "position" parameter which controls the placement of your tweens, labels, callbacks, pauses, and even neste

greensock.com

 

반응형
// router/index.js
export default new VueRouter({
    routes: [
        {
          path: "/portfolio/blog",
          component: () => import("@/views/BlogPage.vue"),
          beforeEnter() {
            window.location.href = "https://kang-ji.tistory.com";
          },
        },
    ]
})
// views/BlogPage.vue

<template>
  <div class="blog-main">blog</div>
</template>

<script>
//import { SidebarMenu } from 'vue-sidebar-menu'

export default {
  created() {
    window.location.href = "https://kang-ji.tistory.com";
  },
};
</script>
// 컴포넌트
<template>
 <router-link tag="button" class="btn trn" to="/portfolio/blog">Blog</router-link>
</template>

외부링크로 이동

 

반응형

 

주의: mask-image는 ie 브라우저 미지원!!! 

 

mixins.scss

// mixin
@mixin svg($path, $width, $height, $color) {
	width: $width;
    height: $height;
    background-color: $color;
    -webkit-mask-image: url($path);
    mask-image: url($path);
    background-size: cover;
    -webkit-background-size: cover;
    mask-size: contain;
    -webkit-mask-position: center;
    mask-position: center;
    -webkit-mask-repeat: no-repeat;
    mask-repeat: no-repeat;
}

 

사용하기 (@include)

// 노랑색 배경의 검정 로고
.logo {
	width: 92px;
    height: 92px;
	background: #ffe31d;
    span {
    	@include svg('~@/assets/images/logo.svg', 78%, 21px, #000);
    }
}

 

호환성

https://caniuse.com/svg-css

 

SVG in CSS backgrounds | Can I use... Support tables for HTML5, CSS3, etc

Method of using SVG images as CSS backgrounds

caniuse.com

 

반응형

css를 사용하여 3D를 만들수 있다.

perspective 속성을 사용하여 원근감을 적용시켜준다.

perspective 속성

perspective 속성은 3D 위치 요소에 약간의 원근감을 주기 위해 z=0 평면과 사용자 사이의 거리를 결정한다.

transform 효과를 주고자하는 부모 요소에 적용.

  • perspective 에 따른 변형 호과
    • perspective가 클수록 (거리가 멀수록) 변형 효과가 적음
    • perspective가 작을수록(거리가 가까울수룩) 변형 효과가 큼
/* Keyword value */
perspective: none;

/* <length> values */
perspective: 20px;
perspective: 3.5em;

/* Global values */
perspective: inherit;
perspective: initial;
perspective: revert;
perspective: revert-layer;
perspective: unset;

 

예제

<div class="card-form">
    <div class="card">A</div>
    <div class="card">B</div>
    <div class="card">C</div>
</div>

 

 

공간에서 보는 시점에서 3D효과를 주게되면 각각의 카드가 원근감에따라 다르게 나타난다.

.card-form {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 60vw;
    height: 60vh;
    background: #fff000;
    perspective: 500px;
}
.card {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100px;
    height: 150px;
    border-radius: 0.5em;
    font-size: 1.5rem;
    background: #14bb8a;
    transform: rotateY(45deg);
}

 

회전되는 요소 자체에 3D효과를 주려면 아래예제 코드처럼 카드요소의 transform안에서 perspective 속성을 부여해준다.

.card-form {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 60vw;
    height: 60vh;
    background: #fff000;
}
.card {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100px;
    height: 150px;
    border-radius: 0.5em;
    font-size: 1.5rem;
  	background: #14bb8a;
    transform: perspective(500px) rotateY(45deg);
}

카드 뒤집기 예제

transform-style 속성 사용 (IE미지원)

See the Pen Untitled by KangJi (@Kangjii) on CodePen.

 

 

transform-style

요소의 자식이 3D 공간에 배치되는지 또는 요소 평면에서 병합되는지 여부를 설정한다.

ie 미지원

transform-style: flat; /* 요소의 자식이 요소 자체의 평면에 있음 */
transform-style: preserve-3d; /* 요소의 자식이 3D 공간에 배치 */

 

backface-visibility

-webkit-backface-visibility: hidden;
backface-visibility: hidden;

 

최종 (IE, Safari 지원)

See the Pen Untitled by KangJi (@Kangjii) on CodePen.

 

https://developer.mozilla.org/ko/docs/Web/CSS/backface-visibility

 

backface-visibility - CSS: Cascading Style Sheets | MDN

CSS backface-visibility 속성은 요소의 뒷면이 사용자를 향할 때 보여야 하는지 지정합니다.

developer.mozilla.org

 

 

https://developer.mozilla.org/en-US/docs/Web/CSS/transform-style

 

transform-style - CSS: Cascading Style Sheets | MDN

The transform-style CSS property sets whether children of an element are positioned in the 3D space or are flattened in the plane of the element.

developer.mozilla.org

 

반응형

1. image-rendering

이미지 랜더링 방식을 바꾼다.

원본이미지 사이즈를 그래도 사용하면 상관없지만 해당 이미지를 확대, 축소할 경우 효과를 볼 수 있다. 

크롬, 사파리 등 브라우저에서 대비를 최적화하여 이미지 랜더링을 하는데 흐린 문제를 해결해줌.

image-rendering: -moz-crisp-edges; /* firefox */
image-rendering: -o-crisp-edges; /* opera */
image-rendering: -webkit-optimize-contrast; /* chrome */
image-rendering: crisp-edges;

 

2. translateZ

z축을 0으로 적용하여 깊이감을 없앤다. 

transform: translateZ(0);

 

3. backface-visibility

뒷면을 hidden처리하여 입체감을 없앤다.

backface-visibility: hidden;

 

반응형

1. Repository 생성

2. 생성해준 저장소에서 Settings > Pages(GitHub Pages) > Source 기존 None을 Main으로 변경 , 기존 Root를 /docs 로 선택 후 Save 저장

 

3. 저장해주면 아래 처럼 url이 세팅됨. 

 

Code 로 돌아가서 Open with Github Descktop 선택 

GithubDesktop.exe 열기

 

 

 

npm run serve 로 프로젝트 실행 

 

 

 

 

 

vue.config.js

module.exports = {
  publicPath: "/portfolio/",
  outputDir: "docs",
};

npm run build를 해준다,

npm run build

npm run build 결과 설정해준 docs폴더내에 컴파일된 파일들이 생성되는 것을 확인 할 수 있다. 

 

이후 Push 하기  터미널에서 아래 순서대로 실행 

git add .
git commit -m "코멘트입력"
git push -u origin main

 

 

 

 

반응형

Vue-cli 프로젝트 생성

 

Vue-cli 설치가 되어있지 않을 경우 전역에 vue/cli 설치해주기

npm install -g @vue/cli

 

 

 

Default ([Vue 2]) 또는 Manually select features(선택하여 설치) 선택하기

Vue3는 안정화되지 않아 추후 의존성 에러 등의 문제를 발생키실 수 있다. 

 

Manually select features 선택시 체크항복

 

2.X 버전 선택

 

CSS 전처리기 선택

 

ESLInt + Prettier 선택

 

Lint on save

 

Lint on save

 

In dedicated config files 각각 별도세팅

 

설치 완료 후 프로젝트 실행하기

cd 프로젝트명
npm run serve

 

 

반응형

 

Adobe Acrobat Reader DC

PDF 문서를 안정적으로 보고, 인쇄하고, 주석을 달 수 있는 글로벌 표준의 무료 소프트웨어


 

Adobe Acrobat Reader DC 오프라인 (내부망,폐쇄망) 전용 Install

https://get.adobe.com/kr/reader/enterprise/

 

Adobe - Adobe Acrobat Reader DC 배포

Adobe Acrobat Reader DC 다운로드 정보: Adobe Acrobat Reader DC는 PDF 문서를 안정적으로 보고, 인쇄하고, 주석을 달 수 있는 글로벌 표준의 무료 소프트웨어입니다. 양식 및 멀티미디어를 포함하여 모든 종

get.adobe.com


 

Adobe Acrobat Reader DC 온라인 공식홈페이지 

https://get.adobe.com/kr/reader/otherversions/

 

모든 버전용 Adobe Acrobat Reader DC 설치

 

get.adobe.com

 

 

반응형

'기타' 카테고리의 다른 글

무료 목업사이트  (0) 2023.08.25

https://vuejsexamples.com/tag/carousel/

 

Carousel - Vue.js Examples

vue-agile Carousel component for Vue.js inspired by Slick. More powerfull with each version, touch-friendly, written in Vue and Vanilla JS (without jQuery dependency). Live Demo https://lukaszflorczak.github.io/vue-agile/ Installation yarn 20 September 201

vuejsexamples.com

https://codepen.io/alvarotrigo/pen/zpQmwq

 

vue-fullpage Issue #103

...

codepen.io

https://splidejs.com/#02

 

Splide - The lightweight, flexible and accessible slider/carousel

Splide is a lightweight, flexible and accessible slider/carousel, written in TypeScript. No dependencies, no Lighthouse errors

splidejs.com

https://antonreshetov.github.io/vue-glide/

 

Vue Glide

 

antonreshetov.github.io

 

반응형

actions 속성을 이용한 로그인 기능 구현과 비동기 처리시 유의할 점

 

SubmitForm 을 실행했을때 데이터를 요청하고 store를 이용하여 컨트롤 되고있는 상태인데 

로그인 이후의 처리로 인해 컴포넌트 단의 코드가 많아짐. 

컴포넌트단(비지니스로직이 많이 노출되지않도록) 코드를 최대한 깔끔하게 하기위한 리팩토링 

 

다른파일에 코드를 옮기는방법

1. store/index.js 에 actions를 이용해서 로그인폼 컴퍼넌트에 있는 로직들을 가져올건데 

우선 actions를 넣어주고 LOGIN함수를 만들고 

api/index.js 의 loginUser를 import 해주고 actions에 loginUser를 호출한다. 

LoginForm에서 로그인처리 로직들을 복사하여 store/index.js actions LOGIN안에 넣는다.

 

// store/index.js
import { loginUser } from '@/api/index.js';

export default new Vuex.Store({
  state: {
  ...
  },
  getters: {
   ...
  },
  mutations: {
   ...
  },
  actions: {
    LOGIN({ commit }) {
		loginUser();
    },
  },
});

 

 

 

반응형

+ Recent posts