使用 Create-React-App 創建 React Styled-Components 及 Sass 開發環境

Angel
Its Ok to Make Mistakes
5 min readJan 15, 2019

為何使用 Styled Components 來創建 Template?

  • Styled Components 建構可複用的 React Component 系統,大幅提高開發效益。
  • Styled Components 僅渲染需要呈現畫面上的部分,不會載入多餘不需要的 code。亦方便追蹤頁面上被渲染的部分。
  • 獨立的 Class Name 可避免 Class Name 重複、複寫、拼字錯誤等問題。
  • 避免 CSS 系統難以追蹤哪個 Class 沒有被使用到。Styled-Components 在開發中可以輕易追蹤沒有被使用到的 Components,予以刪除。
  • 使用判斷動態改變 Theme 的狀態,無須手動管理許多的 Class。
  • 維護上可減少跨檔案尋找哪個 CSS Style 造成的全域污染。
  • 自動處理所有瀏覽器前綴詞。

第ㄧ步:建立 Create-React-App

$ npx create-react-app <my-app>
$ cd <my-app>
$ yarn start

此時可以從瀏覽器看到 Create-React-App 的 Demo。
http://localhost:3000/

  • 更新 Create-React-App
npm install react-script@latest

第二步:建立 Styled Components

$ yarn add styled-components

建立 src 資料夾 加入 components 資料夾放 styles

$ mkdir src/components
$ touch src/components/button.js src/components/typography.js

加入 styles 在 typography.js 檔案中

import styled from 'styled-components'export const H1 = styled.h1`
font-size: 30px;
`
export const H2 = styled.h2`
font-size: 24px;
`
export const H3 = styled.h3`
font-size: 18px;
`
export const H4 = styled.h4`
font-size: 15px;
`

加入 styles 在 button.js 檔案中

import styled from 'styled-components'export default styled.button`
background-color: #DB7290;
color: white;
padding: 0px 32px;
text-align: center;
cursor: pointer;
border-radius: 10px;
border: none;
`

在 App.js 檔案引入 React 及測試檔 typography 和 button,export 測試的 template

import React, { Component } from 'react';
import { H1, H2, H3, H4 } from './components/typography'
import { default as Button } from './components/button'
class App extends Component {
render() {
return (
<div className="App">
<div>
<H1>Heading 1</H1>
<H2>Heading 2</H2>
<H3>Heading 3</H3>
<H4>Heading 4</H4>
<Button type="submit"><H3>Hello world</H3></Button>
</div>
</div>
);
}
}
export default App;

Server 再 run 一次 $ yarn start 看成果,即完成第一個 React Styled Component 的 Demo

第三步:加入 Sass 複合使用

雖然 React Styled-Components 會希望將 Sass 完全拆除,但在既有專案移植期間,仍然會需要使用 Sass

$ yarn add node-sass

在 src 資料夾加入 sass 資料夾及檔案

$ mkdir src/sass
$ touch src/sass/style.scss

貼上測試用 Scss

@mixin bg($padding) {
background-image: linear-gradient(to bottom, #F1AD56, #DB7290);
padding: $padding;
}
div {
text-align: center;
color: white;
@include bg(10px);
button {
&:hover {
background-color: #FFD0DD;
color: #DB7290;
}
}
}

到 App.js 引入

import './sass/style.scss';

存檔後,如果沒有報錯,即可看到 Sass 與 Styled-Components 共同運作的畫面。

Say hello! 我是 Angel,這裏的內容如果有幫到你,希望能獲得一些拍手作為鼓勵 
工作上的合作歡迎隨時透過 Mail 聯繫我 contact@aneglho.design

Thanks for watching!

--

--

Angel
Its Ok to Make Mistakes

A web / UIUX designer, in digital entertainment industry, Taipei Taiwan.