728x90

SSL 인증서 중 Comodo  인증서가 sectigo 인증서로 변경되면서 일부 리눅스 시스템 내 Root/chain 인증서가 반영이 안되 어  있어 JAVA SSL HandshakeException 및 Curl  오류가 발생합니다.

 

 

"Sectigo(COMODO)의 “AddTrust External Root CA” 만료 이후 HTTPS 접속 오류 현상 관련 안내드립니다." 에서 확인이 가능합니다.

www.certkorea.co.kr/bbs/board.php?bo_table=31&wr_id=30

 

Sectigo(COMODO)의 “AddTrust External Root CA” 만료 이후 HTTPS 접속 오류 현상 관련 안내드립니다. > 공지�

> 고객지원/이벤트 > 공지사항 공지사항

www.certkorea.co.kr

 

오류 2 . javax.net.ssl.SSLHandshakeException

javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

 

 

이와 같은 경우에는 keytool을 이용해서 인증서를 추가해줘야 합니다.

 

Chain_RootCA_Bundle.zip
0.05MB

 

# keytool 로 인증서 추가하기

 

# cd ${JAVA_HOME}/jre/lib/security/cacerts
# keytool -list -keystore ${JAVA_HOME}/jre/lib/security/cacerts
키 저장소 비밀번호 입력:  changeit

 

# keytool -import -keystore ${JAVA_HOME}/jre/lib/security/cacerts -file "CA Root 인증서"  -alias "인증서별칭"

예) 

# cd ${JAVA_HOME}/jre/lib/security/cacerts

# keytool -list -keystore ${JAVA_HOME}/jre/lib/security/cacerts

키 저장소 비밀번호 입력:  changeit
키 저장소 비밀번호 입력:  
키 저장소 유형: JKS
키 저장소 제공자: SUN
키 저장소에 104개의 항목이 포함되어 있습니다.

verisignclass2g2ca [jdk], 2016. 8. 26, trustedCertEntry, 
인증서 지문(SHA1): B3:EA:C4:47:76:C9:C8:1C:EA:F2:9D:95:B6:CC:A0:08:1B:67:EC:9D
digicertassuredidg3 [jdk], 2016. 8. 26, trustedCertEntry, 
인증서 지문(SHA1): F5:17:A2:4F:9A:48:C6:C9:F8:A2:00:26:9F:DC:0F:48:2C:AB:30:89
verisignuniversalrootca [jdk], 2016. 8. 26, trustedCertEntry, 
인증서 지문(SHA1): 36:79:CA:35:66:87:72:30:4D:30:A5:FB:87:3B:0F:A7:7B:B7:0D:54
digicerttrustedrootg4 [jdk], 2016. 8. 26, trustedCertEntry, 
인증서 지문(SHA1): DD:FB:16:CD:49:31:C9:73:A2:03:7D:3F:C8:3A:4D:7D:77:5D:05:E4
verisignclass1g3ca [jdk], 2016. 8. 26, trustedCertEntry, 
인증서 지문(SHA1): 20:42:85:DC:F7:EB:76:41:95:57:8E:13:6B:D4:B7:D1:E9:8E:46:A5
identrustpublicca [jdk], 2016. 8. 26, trustedCertEntry, 

# keytool -import -keystore ${JAVA_HOME}/jre/lib/security/cacerts -file "Chain_RootCA_Bundle.crt" -alias "sectigorsatrust"

........
#5: ObjectId: 2.5.29.32 Criticality=false
CertificatePolicies [
  [CertificatePolicyId: [2.5.29.32.0]
[]  ]
  [CertificatePolicyId: [2.23.140.1.2.1]
[]  ]
]

#6: ObjectId: 2.5.29.37 Criticality=false
ExtendedKeyUsages [
  serverAuth
  clientAuth
]

#7: ObjectId: 2.5.29.15 Criticality=true
KeyUsage [
  DigitalSignature
  Key_CertSign
  Crl_Sign
]

#8: ObjectId: 2.5.29.14 Criticality=false
SubjectKeyIdentifier [
KeyIdentifier [
0000: 8D 8C 5E C4 54 AD 8A E1   77 E9 9B F9 9B 05 E1 B8  ..^.T...w.......
0010: 01 8D 61 E1                                        ..a.
]
]

이 인증서를 신뢰합니까? [아니오]:  y
인증서가 키 저장소에 추가되었습니다.

 

# 추가한 인증서를 삭제하고자 할 경우 

# keytool -delete -alias "알리아스인증서명칭" -keystore "cacerts가 있는 경로"

예) keytool -delete -alias "usertrustrsacaroot" -keystore ${JAVA_HOME}/jre/lib/security/cacerts 

 


 

참고 URL

blog.naver.com/kgj1/220584997842
www.securesign.kr/guides/kb/47

m.blog.naver.com/PostView.nhn?blogId=toy_ssl&logNo=110168927395&proxyReferer=https:%2F%2Fwww.google.com%2F

 

 

728x90

SSL 인증서 중 Comodo  인증서가 sectigo 인증서로 변경되면서 일부 리눅스 시스템 내 Root/chain 인증서가 반영이 안되 어  있어 JAVA SSL HandshakeException 및 Curl  오류가 발생합니다.

 

"Sectigo(COMODO)의 “AddTrust External Root CA” 만료 이후 HTTPS 접속 오류 현상 관련 안내드립니다." 에서 확인이 가능합니다.

www.certkorea.co.kr/bbs/board.php?bo_table=31&wr_id=30

 

Sectigo(COMODO)의 “AddTrust External Root CA” 만료 이후 HTTPS 접속 오류 현상 관련 안내드립니다. > 공지�

> 고객지원/이벤트 > 공지사항 공지사항

www.certkorea.co.kr

 

오류 1 . curl https://www.OOOOO.co.kr cli 명령시 에러 발생

인증서가 교체 된 이후에 https://www.OOOO.co.kr로 접속할 경우 원할하지 않은 부분이 발생할 수 있습니다.

예를 들어 아래와 같은 문제가 발생할 수 있습니다.

# curl https://www.OOOOO.co.kr

curl performs SSL certificate verification by default, using a "bundle"
 of Certificate Authority (CA) public keys (CA certs). If the default
 bundle file isn't adequate, you can specify an alternate file
 using the --cacert option.
If this HTTPS server uses a certificate signed by a CA represented in
 the bundle, the certificate verification probably failed due to a
 problem with the certificate (it might be expired, or the name might
 not match the domain name in the URL).
If you'd like to turn off curl's verification of the certificate, use
 the -k (or --insecure) option.

 

 

 

위와 같이 에러가 뜬다면 

 

서버의 인증서 Root CA 를 추가해 줘야 합니다.

 

0.  먼저 CA 파일의 경로를 찾습니다.

아래와 같이 curl -v https://www.OOOOO.co.kr로 하면 CAfile 파일 경로 위치를 확인할 수 있습니다.


1. 먼저 서버에 Chain_RootCA_Bundle.zip 압축파일을 풀어서 ftp로 업로드 합니다.
2. 업로드된 파일로 콘솔로 들어가야 함.

# cd ./Chain_RootCA_Bundle 
# ll /etc/pki/tls/certs/ca-bundle.crt
# cp /etc/pki/tls/certs/ca-bundle.crt /etc/pki/tls/certs/ca-bundle.crt.20201006
# printf "\n### Sectigo_RSA_AddTrust_codesign Add $(date '+%Y.%m.%d') \n " >> /etc/pki/tls/certs/ca-bundle.crt
# cat Chain_RootCA_Bundle.crt | sed -e "s/\\r//g" >>  /etc/pki/tls/certs/ca-bundle.crt

Chain_RootCA_Bundle.zip
0.05MB

 

첨부파일을 보시고서 자신에 맞는 폴더에서 확인 작업하시면 됩니다.

[15:35:43 root@home:~#] ll /etc/pki/tls/certs/ca-bundle.crt
lrwxrwxrwx 1 root root 49  5월 20  2016 /etc/pki/tls/certs/ca-bundle.crt -> /etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem

[15:35:52 root@home:~#] cp /etc/pki/tls/certs/ca-bundle.crt /etc/pki/tls/certs/ca-bundle.crt.20201006


[15:36:28 root@home:/home#] cd Chain_RootCA_Bundle/
[15:36:32 root@home:/home/Chain_RootCA_Bundle#] ls
ChainCA1.crt  ChainCA2.crt  Chain_RootCA_Bundle.crt  RootCA.crt  add_sectigo_cert.sh

[15:36:33 root@home:/home/Chain_RootCA_Bundle#] printf "\n### Sectigo_RSA_AddTrust_codesign Add $(date '+%Y.%m.%d') \n " >> /etc/pki/tls/certs/ca-bundle.crt
[15:36:50 root@home:/home/Chain_RootCA_Bundle#] cat Chain_RootCA_Bundle.crt | sed -e "s/\\r//g" >>  /etc/pki/tls/certs/ca-bundle.crt
[15:36:53 root@home:/home/Chain_RootCA_Bundle#] curl https://www.OOOOOO.co.kr
....

 

 

 


참고 URL

www.securesign.kr/guides/kb/47

louky0714.tistory.com/entry/Linux-sectigo-rootchain-%EC%9D%B8%EC%A6%9D%EC%84%9C-%EC%B6%94%EA%B0%80

 

728x90

크롬(Chrome) 쿠키 삭제 방법

< 첫번째 방법 >

1. 크롬에서 Ctrl + Shift + Del 누릅니다.

2. 기간을전체 기간으로 바꾸고, 인터넷 사용 기록 삭제 버튼을 누릅니다.

 

 

<두번째 방법>

1.  크롬 우측 상단 위  :  을 클릭합니다
   2. 설정(S)을 클릭 합니다. 
   3.  "고급"  을 클릭합니다.

 

 

4. 인터넷 사용 기록 삭제를 클릭합니다.
5. 기간을 전체 기간으로 바꾸고, 인터넷 사용 기록 삭제를 합니다.

 


엣지 쿠키 삭제 방법

<첫번째 방법>

1. 엣지 에서 Ctrl + Shift + Del 을 누릅니다.
2. 시간 범위를 ‘모든 시간’ 으로 바꾸고, 지금 지우기 버튼을 누릅니다.

 

 

<두번째 방법>

1. 엣지 우측 상단 위  ...    을 클릭합니다
2. 설정을 클릭 합니다. 
3. 개인 정보 및 서비스를 클릭합니다.

 

 

4. 지울 항목 선택을 클릭합니다.
5. 시간 범위를 ‘모든 시간’ 으로 바꾸고, 지금 지우기 버튼을 누릅니다.

 

 

728x90

참고URL

리눅스 메모리 사용률 확인

zetawiki.com/wiki/%EB%A6%AC%EB%88%85%EC%8A%A4_%EB%A9%94%EB%AA%A8%EB%A6%AC_%EC%82%AC%EC%9A%A9%EB%A5%A0_%ED%99%95%EC%9D%B8

 

Nginx, PHP-FPM에서 child process 개수 결정하기

yumere.tistory.com/81


# 프로세스중 메모리를 많이 사용하는 프로세스 리스트를 뽑아낸다.

# ps -ef --sort -rss

# ps -ef --sort -rss

UID        PID  PPID  C STIME TTY          TIME CMD
root     14801     1  0 Aug24 ?        00:00:36 /usr/local/apache/bin/httpd -k start
root     30654     1  0 Aug26 ?        00:03:02 java -jar ../server/tubro-site-main-1.0.0-SNAPSHOT.jar --server.port=8182
root     30607     1  0 Aug26 ?        00:02:43 java -jar ../server/test-swagger-1.0.0-SNAPSHOT.jar --server.port=8181
nobody     396 14801  0 Aug26 ?        00:00:44 /usr/local/apache/bin/httpd -k start
nobody     395 14801  0 Aug26 ?        00:00:50 /usr/local/apache/bin/httpd -k start
nobody    3556 14801  0 Aug26 ?        00:00:45 /usr/local/apache/bin/httpd -k start
nobody   32734 14801  0 Aug26 ?        00:00:50 /usr/local/apache/bin/httpd -k start
mysql    30313 29796  0  2019 ?        02:31:44 /usr/local/mysql/bin/mysqld --basedir=/usr/local/mysql --datadir=/home/mysql/data --plugin-dir=/usr/local/mysql/lib/plu
root     11757     1  0  2019 ?        00:29:47 /sbin/rsyslogd -i /var/run/syslogd.pid -c 5
root      3203 15675  0 18:15 ?        00:00:00 sshd: hanchiro [priv]
root      3233  3206  0 18:15 pts/0    00:00:00 su -
root      3235     1  0 18:15 ?        00:00:00 /usr/libexec/fprintd

 

 

# php-fpm 프로세스중에서 메모리를 많이 사용하는 리스트를 뽑아낸다.

# ps -ylC php-fpm --sort:rss

 

#java 프로세스의 메모리 사용량을 볼 수 있다.
ps -ylC java --sort:rss

# ps -ylC java --sort:rss
S   UID   PID  PPID  C PRI  NI   RSS    SZ WCHAN  TTY          TIME CMD
S     0 30607     1  0  80   0 510144 1473060 futex_ ?     00:02:43 java
S     0 30654     1  0  80   0 859748 1542193 futex_ ?     00:03:02 java

RSS를 보면 평균 사용 메모리를 KB로 표시해준다.
위 명령어 외에 좀 더 확실해게 보려면 아래 명령어를 입력해보면 된다.

 

PHP-FPM으로 사용가능한 memory / Processor 당 메모리 사용량으로 나누면 pm.max_children 개수를 정할 수 있다.
ps --no-headers -o "rss,cmd" -C java | awk '{ sum+=$1 } END { printf ("%d%s\n", sum/NR/1024,"Mb") }'

# ps --no-headers -o "rss,cmd" -C java | awk '{ sum+=$1 } END { printf ("%d%s\n", sum/NR/1024,"Mb") }'
668Mb


<< bash 스크립트 >>

#!/bin/bash

TOTAL=`free | grep ^Mem | awk '{print $2}'`
USED1=`free | grep ^Mem | awk '{print $3}'`
USED2=`free | grep ^-/+ | awk '{print $3}'`

NOMINAL=$((100*USED1/TOTAL))
ACTUAL=$((100*USED2/TOTAL))

MEMTOTLA=`cat /proc/meminfo | grep MemTotal`

# NOMINAL=`echo "100*$USED1/$TOTAL" | bc -l`
# ACTUAL=`echo "100*$USED2/$TOTAL" | bc -l`

echo '--------------------------------------------------'
echo ${MEMTOTLA}

echo NOMINAL=${NOMINAL:0:5}% ACTUAL=${ACTUAL:0:5}%
echo '--------------------------------------------------'
echo 'NOMINAL : 명목, ACTUAL : 실질, rss : 물리메모리'
echo '--------------------------------------------------'
echo '물리메모리 사용량 TOP 10'
ps -eo user,pid,ppid,rss,size,vsize,pmem,pcpu,time,comm --sort -rss | head -n 11
echo '--------------------------------------------------'
echo 'SWAP메모리 사용량 TOP 10'
ps -eo user,pid,ppid,rss,size,vsize,pmem,pcpu,time,comm --sort -size | head -n 11

[root@KSERVER145-25 ~]# ./memory_check.sh 
--------------------------------------------------
MemTotal: 7894176 kB
NOMINAL=98% ACTUAL=37%
--------------------------------------------------
NOMINAL : 명목, ACTUAL : 실질, rss : 물리메모리
--------------------------------------------------
물리메모리 사용량 TOP 10
USER       PID  PPID   RSS    SZ    VSZ %MEM %CPU     TIME COMMAND
root     14801     1 4342480 6220 4624664 55.0 0.0 00:00:36 httpd
root     30654     1 859844 6019212 6168772 10.8 0.0 00:03:02 java
root     30607     1 510144 5742716 5892240  6.4 0.0 00:02:43 java
nobody     396 14801 291316 5440208 10060724  3.6 0.0 00:00:44 httpd
nobody     395 14801 280584 5438416 10058960  3.5 0.0 00:00:51 httpd
nobody    3556 14801 270376 5438416 10058932  3.4 0.0 00:00:45 httpd
nobody   32734 14801 257716 5438416 10058960  3.2 0.0 00:00:50 httpd
mysql    30313 29796 163408 4145948 4183520  2.0 0.0 02:31:44 mysqld
root     11757     1  5088 228600 256192  0.0 0.0 00:29:47 rsyslogd
root      3203 15675  4120   616  73456  0.0  0.0 00:00:00 sshd
--------------------------------------------------
SWAP메모리 사용량 TOP 10
USER       PID  PPID   RSS    SZ    VSZ %MEM %CPU     TIME COMMAND
root     30654     1 859844 6019212 6168772 10.8 0.0 00:03:02 java
root     30607     1 510144 5742716 5892240  6.4 0.0 00:02:43 java
nobody     396 14801 291316 5440208 10060724  3.6 0.0 00:00:44 httpd
nobody     395 14801 280584 5438416 10058960  3.5 0.0 00:00:51 httpd
nobody    3556 14801 270376 5438416 10058932  3.4 0.0 00:00:45 httpd
nobody   32734 14801 257716 5438416 10058960  3.2 0.0 00:00:50 httpd
mysql    30313 29796 163408 4145948 4183520  2.0 0.0 02:31:44 mysqld
root      2399     1   812 4078160 4116684  0.0 0.0 00:00:01 console-kit-dae
root     11757     1  5088 228600 256192  0.0 0.0 00:29:47 rsyslogd
68        1904     1  1076 11216  38212  0.0  0.0 00:09:54 hald

memory_check.sh.zip
0.00MB

 

728x90

종종 빨간색으로 뜨는 글자들에는 Cannot resolve symbol 'java', 'String', 'Scanner' 등이 제대로 import 되지 않고서 에러가 뜰 때가 있습니다.

이런 현상의 가장 큰 원인은 Module SDK is not defined 이라는 에러로 Moduel SDK가 제대로 정의되지 않아서 생기는 에러가 일 가능성이 있습니다.

종종 IntelliJ를 업데이트를 하면서 IntelliJ의 JAVA  버전으로 설정하고 사용하는 경우에 발생할 수 있습니다.

JAVA 버전이 업데이트 되면서 기존에 사용하던 JAVA 설치 파일 경로의 링크가 변경되는 경우가 있기 때문입니다.

 

그래서 IntelliJ의 JAVA 설정을 변경해줘야 합니다.

 

Proejct Structure에서 Platform Settings  > SDKs 를 누릅니다.

 

+ 를 눌러서 Add New SDK 에서 JDK를 선택합니다.

 

새로 설치한 JAVA 버전이 있는 경로롤 찾아서 선택해 줍니다.

Apply 버전을 눌러서 적용시킨 다음에 "OK" 파란색 버튼을 눌러주세요.

 

그러면 새롭게 지정된 JAVA버전에 맞게 intelliJ가 index을 새롭게 구축하게 됩니다.

이렇게하면 java 버전에 맞게 모듈이 새롭게 구축되어 에러가 나타나진 않을 것입니다.

 

 

Module SDK is not defined / Cannot resolve symbol 'java', 'String', 'Scanner' 등이 빨간색

728x90

IntelliJ IDEA를 쓰고 있으며, 멀쩡히 잘 쓰다가 종종 잊을만하면 Cannot resolve symbol.. 에러가 날때가 있습니다.

 

예를 들면 아래와 같이 import가 제대로 안되어 있는 경우가 그런 경우입니다.

cannot resolve symbol import org.openjdk.jmh.runner.options.Options;

시도 방법 1

상단 메뉴바에서 Build > Clean Project 하고나서 Build > Rebuild Project를 해줍니다.

 

시도 방법 2

시도 방법 1로도 해결이 안되면 캐시를 비우고 재실행 해봅니다.

상단 메뉴바에서 File > Invalidate Caches / Restart…를 선택하고 IDE를 재실행합니다.

 

 

 

 
728x90

출처

https://ddolcat.tistory.com/26

http://blog.naver.com/PostView.nhn?blogId=netrance&logNo=221224761858&parentCategoryNo=&categoryNo=95&viewDate=&isShowPopularPosts=true&from=search

 

 

앱을 삭제했을 때 shared preference 데이터를 삭제하는 방법
How to remove shared preference while application uninstall in android

 

앱을 삭제 후 재설치하게 되면 공유환경 설정(shared preference)에서 일부 데이터가 복원되는 증상이 요즈음 나온 최신 폰에서 발생하고 있습니다.

즉, 앱을 삭제 후 재설치하면, 삭제 전에 저장되었던 자료들이 남아있는 문제가 발견되고 있습니다.

 

원인은 바로 자동 백업 "BackupManager" 때문 -- android:allowBackup 속성 true로 자동 설정

Android API 23(또는 Android "6.0" 또는 Android "Marshmellow")이후 BackupManager는 공유 환경 설정을 포함한 앱의 모든 데이터를 클라우드에 저장합니다.

이는 안드로이드 6.0부터는 AndroidManifest.xml 파일에서 application 요소의 android:allowBackup 속성을 명시하지 않으면 자동으로 true로 설정하기 때문인데 이로 인해 사용자도 모르게 데이터가 구글 클라우드에 자동으로 백업됩니다.

 

결국 앱 삭제 후 재설치하면, 자료가 자동으로 복원되다 보니 환경설정(preferences)에 저장된 자료가 되살아 나는 것입니다.

 


해결방법

 

1. 안드로이드 폰에서 직접 해제 하는 방법이 있습니다.
   설정 > 백업 및 재설정 > 자동복원을 선택, 자동복원 해제 를 하는 방법입니다.
   그러나 이 방법은 장치에 설치된 모든 응용 프로그램의 자동 백업기능을 해제하기 때문에 권장하지 않습니다.


2. 앱 소스에서 매니페스트 파일로 이동, application 태그에서 "allowBackup" 속성을 찾아서 false로 설정하는 것입니다.

 


앱의 데이터 자동 백업을 막는 방법

 

1. AndroidManifest.xml 파일을 여세요.

 

2. application 요소에 android:allowBackup 요소를 추가하고, 값을 false로 설정하세요.

android:allowBackup="false"

 

3. application 요소에 android:fullBackupContent 요소를 추가하고, 값을 false로 설정하세요.

android:fullBackupContent="false"

 

4. (옵션) 프로젝트에 다른 플러그인이 있는 경우, allowBackup 속성이 충돌할 수 있습니다.

    이 경우 application 요소에 tools:replace 속성을 추가하고, 값은 "android:allowBackup"으로 설정합니다.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          xmlns:tools="http://schemas.android.com/tools"
          package="패키지명">

    <uses-feature
        android:name="android.hardware.camera"
        android:required="true"/>

    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
    <uses-permission android:name="android.permission.INTERACT_ACROSS_USERS_FULL"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>


......


    <application
        android:name=".MyApp"

        android:allowBackup="false"
        android:fullBackupContent="false"
        tools:replace="android:allowBackup"
        
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme"
        android:usesCleartextTraffic="true"
        tools:replace="android:icon">

......


    </application>

</manifest>

 

참고로 android:fullbackupOnly="false" 기능은 안드로이드 API 21 이후 폰에서 설정, 사용가능합니다.

 

 

<기타 참고 사이트>

https://stackoverflow.com/questions/33169618/an-android-app-remembers-its-data-after-uninstall-and-reinstall

https://developer.android.com/guide/topics/data/autobackup.html

http://androbook.tistory.com/entry/%EB%8B%A4%EC%8B%9C-%EC%82%B4%ED%8E%B4%EB%B3%B4%EB%8A%94-%EB%A7%A4%EB%8B%88%ED%8E%98%EC%8A%A4%ED%8A%B8-%EC%86%8D%EC%84%B1%EB%93%A4

 

728x90

참고 URL : gmlwjd9405.github.io/2018/05/25/git-add-cancle.html

 

git으로 commit 을 하는데 잘못 commit 하였다면 취소할 수 있습니다.

각 단계별로 취소하는 방법이 있습니다.

 

1. git add를 취소할 수 있다.
2. git commit을 취소할 수 있다.
3. git push를 취소할 수 있다.
4. untracked 파일을 삭제할 수 있다.

 

intelij 에서 git commit을 하는 경우 Rollback..으로 할 수 있으나 Terminal 을 열어서 하는게 더 나을 수도 있습니다.

 


git add 취소하기 (파일 상태를 Unstage로 변경하기)

 

$ git reset HEAD

 

아래와 같이 실수로 git add * 명령을 사용하여 모든 파일을 Staging Area에 넣는 경우가 발생하였다면 

$ git add *
// 파일들의 상태를 확인한다.
$ git status
On branch master
Changes to be committed:
(use "git reset HEAD <file>..." to unstage)
  renamed:    README.md -> README
  modified:   CONTRIBUTING.md

 

 

뒤에 파일명이 없으면 add한 파일 전체를 취소할 수 있습니다.

$ git reset HEAD
// 파일들의 상태를 확인한다.

$ git status
On branch master
Changes to be committed:
(use "git reset HEAD <file>..." to unstage)
........

 

git add 한 파일중에서 README 파일을 Unstage로 변경할 수 있습니다.

$ git reset HEAD 파일명

$ git reset HEAD README
Unstaged changes after reset:
M	README


-- 파일들의 상태를 확인합니다.

$ git status
On branch master
Changes to be committed:
(use "git reset HEAD <file>..." to unstage)
  renamed:    README.md -> README
Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git checkout -- <file>..." to discard changes in working directory)
  modified:   README

 


git commit 취소하기  (git reset HEAD^)

 

commit이 완료된 경우 취소할 수 있습니다.
어떤 파일을 빼먹고 commit한 경우나 너무 일찍 commit 한 경우 등에서

git reset HEAD^ 명령어를 통해 git commit을 취소할 수 있습니다.

-- commit 목록 확인을 확인합니다.
$ git log



-- 1. commit을 취소하고 해당 파일들은 staged 상태로 유지하고, 워킹 디렉터리에 보존합니다.
$ git reset --soft HEAD^



-- 2. commit을 취소하고 해당 파일들은 unstaged 상태로 변경하고, 워킹 디렉터리에 보존합니다.
$ git reset --mixed HEAD^ // 기본 옵션
$ git reset HEAD^         // 위와 동일
$ git reset HEAD~2        // 마지막 2개의 commit을 취소



-- 3. commit을 취소하고 해당 파일들은 unstaged 상태로 변경하고, 워킹 디렉터리에서도 삭제합니다.
$ git reset --hard HEAD^

 

(실제 사용한 예)

$ git reset HEAD^
리셋 뒤에 스테이징하지 않은 변경 사항:
M       ...........
M       .....


$

 

 

git reset 명령은 아래의 옵션과 관련해서 주의하여 사용해야 합니다.

 

reset 옵션

–soft : index 보존(add한 상태, staged 상태), 워킹 디렉터리의 파일 보존. 즉 모두 보존.
–mixed : index 취소(add하기 전 상태, unstaged 상태), 워킹 디렉터리의 파일 보존 (기본 옵션)
–hard : index 취소(add하기 전 상태, unstaged 상태), 워킹 디렉터리의 파일 삭제. 즉 모두 취소.

 

 

만약 워킹 디렉터리를 원격 저장소의 마지막 commit 상태로 되돌리고 싶으면, 아래의 명령어를 사용해야 합니다.

단, 이 명령을 사용하면 원격 저장소에 있는 마지막 commit 이후의 워킹 디렉터리와 add했던 파일들이 모두 사라지므로 주의해야 합니다.

-- 워킹 디렉터리를 원격 저장소의 마지막 commit 상태로 되돌린다.

$ git reset --hard HEAD

 


commit message 변경하기 (git commit -ament "메세지")

commit message를 잘못 적은 경우, git commit –amend 명령어를 통해 git commit message를 변경할 수 있습니다.

$ git commit --amend

 


git push 취소하기

 

이 명령을 사용하는 것은 자신의 local의 내용을 remote에 강제로 덮어쓰기를 하는 것이기 때문에 주의해야 합니다.

왜냐하면 되돌아간 commit 이후의 모든 commit 정보가 사라지기 때문에 주의를 해야 하는 것입니다.

특히, 협업 프로젝트에서는 동기화 문제가 발생할 수 있으므로 팀원과 꼭 상의하셔야 합니다.

 

원격 저장소에 push하여 저장되어 있는 경우는 아래와 같은 단계로 취소할 수 있습니다.

 

1단계 : 원하는 시점으로 워킹 디렉터리를 되돌립니다.

2단계 : 되돌려진 상태에서 다시 commit을 합니다.

3단계 : 원격 저장소에 강제로 push 합니다.

-- 1단계 : 가장 최근의 commit을 취소합니다. (기본 옵션: --mixed)
$ git reset HEAD^

-- 1단계 : 원하는 시점으로 워킹 디렉터리가 되었는지 확인합니다.
-- 1단계 : Reflog(브랜치와 HEAD가 지난 몇 달 동안에 가리켰었던 커밋) 목록 확인

$ git reflog 
또는 
$ git log -g


-- 1단계 : 원하는 시점으로 워킹 디렉터리를 되돌립니다.
$ git reset HEAD@{number} 
또는 
$ git reset [commit id]

-- 2단계 : 되돌려진 상태에서 다시 commit을 합니다.
$ git commit -m "Write commit messages"


-- 2단계 : 원격 저장소에 강제로 push 합니다.
$ git push origin [branch name] -f
또는
$ git push origin +[branch name]

-- 예를 들어 master branch를 원격 저장소(origin)에 강제로 push하겠다고 한다면
$ git push origin +master

 


추적중이지 않은 파일 삭제하기 : git clean

 

git clean 명령은 추적 중이지 않은 파일만 지우는 명령입니다.

하지만 .gitignore 에 명시하여 무시되는 파일은 지우지 않지 않습니다.

$ git clean -f         // 디렉터리를 제외한 파일들만 삭제
$ git clean -f -d      // 디렉터리까지 삭제
$ git clean -f -d -x   // 무시된 파일까지 삭제

 

-d 옵션  : 디렉터리까지 지우는 것
-x 옵션  : 무시된 파일(.DS_Store나 .gitignore에 등록한 확장자 파일들)까지 모두 지우는 것
     Ex) .o 파일 같은 빌드 파일까지도 지울 수 있다.
-n 옵션  : 가상으로 실행해보고 어떤 파일들이 지워질지 알려주는 것

728x90

create-react-app을 이용한 React 초기 개발 환경 설정

참고URL

https://xiubindev.tistory.com/92 

https://velog.io/@cjy9306/create-react-app%EC%97%90%EC%84%9C-react%EA%B0%80-%EC%8B%A4%ED%96%89%EB%90%98%EB%8A%94-%EA%B8%B0%EB%B3%B8-%EC%9B%90%EB%A6%AC-yjk56rqzlk

 

Yarn - 개선된 버전의 npm

리눅스, 혹은 macOS 에서 nvm 을 통하여 Node.js 를 설치했다면 yarn global 설치가 제대로 작동하기 위해선 다음 커맨드를  profile에 입력해줘야 합니다.

-- macOS
$ echo 'export PATH="$(yarn global bin):$PATH"' >> ~/.bash_profile

-- Linux
$ echo 'export PATH="$(yarn global bin):$PATH"' >> ~/.bashrc

 

1. create-react-app 설치

$ npm install -g create-react-app

또는 

$ yarn global add create-react-app

 

2. react app 생성

$ create-react-app first-react-app

 


 

$ npx create-react-app firstReactApp

카멜방식의 프로젝트는 생성할 수 없습니다.

단어사이에 대문자를 넣지 말고 "-" 으로 표기하여 폴더를 생성하여야 합니다.

$ npx create-react-app firstReactApp

npx: 98개의 패키지를 3.66초만에 설치했습니다.
Cannot create a project named "firstReactApp" because of npm naming restrictions:

  * name can no longer contain capital letters

Please choose a different project name.


$ cd firstReactApp
-bash: cd: firstReactApp: No such file or directory

 

$ npx create-react-app first-react-app

리엑트 프로젝트 생성 

$ npx create-react-app first-react-app
npx: 98개의 패키지를 3.102초만에 설치했습니다.

Creating a new React app in /Users/jaehonghan/dev/workspace_nodejs/first-react-app.

Installing packages. This might take a couple of minutes.
Installing react, react-dom, and react-scripts with cra-template...

yarn add v1.22.4
[1/4] 🔍  Resolving packages...
[2/4] 🚚  Fetching packages...
[3/4] 🔗  Linking dependencies...
warning "react-scripts > @typescript-eslint/eslint-plugin > tsutils@3.17.1" has unmet peer dependency "typescript@>=2.8.0 || >= 3.2.0-dev || >= 3.3.0-dev || >= 3.4.0-dev || >= 3.5.0-dev || >= 3.6.0-dev || >= 3.6.0-beta || >= 3.7.0-dev || >= 3.7.0-beta".
[4/4] 🔨  Building fresh packages...
[1/4] ⡀ fsevents
[-/4] ⡀ waiting...
[-/4] ⡀ waiting...
warning Error running install script for optional dependency: "/Users/jaehonghan/dev/workspace_nodejs/first-react-app/node_modules/fsevents: Command failed.
Exit code: 1
Command: node-gyp rebuild
Arguments: 
Directory: /Users/jaehonghan/dev/workspace_nodejs/first-react-app/node_modules/fsevents
Output:
gyp info it worked if it ends with ok
gyp info using node-gyp@5.1.0
gyp info using node@14.4.0 | darwin | x64
gyp info find Python using Python version 2.7.16 found at \"/System/Library/Frameworks/Python.framework/Versions/2.7/Resources/Python.app/Contents/MacOS/Python\"
gyp info spawn /System/Library/Frameworks/Python.framework/Versions/2.7/Resources/Python.app/Contents/MacOS/Python
gyp info spawn args [
gyp info spawn args   '/usr/local/Cellar/node/14.4.0/libexec/lib/node_modules/npm/node_modules/node-gyp/gyp/gyp_main.py',
gyp info spawn args   'binding.gyp',
gyp info spawn args   '-f',
gyp info spawn args   'make',
gyp info spawn args   '-I',
gyp info spawn args   '/Users/jaehonghan/dev/workspace_nodejs/first-react-app/node_modules/fsevents/build/config.gypi',
gyp info spawn args   '-I',
gyp info spawn args   '/usr/local/Cellar/node/14.4.0/libexec/lib/node_modules/npm/node_modules/node-gyp/addon.gypi',
gyp info spawn args   '-I',
gyp info spawn args   '/Users/jaehonghan/Library/Caches/node-gyp/14.4.0/include/node/common.gypi',
gyp info spawn args   '-Dlibrary=shared_library',
gyp info spawn args   '-Dvisibility=default',
gyp info spawn args   '-Dnode_root_dir=/Users/jaehonghan/Library/Caches/node-gyp/14.4.0',
gyp info spawn args   '-Dnode_gyp_dir=/usr/local/Cellar/node/14.4.0/libexec/lib/node_modules/npm/node_modules/node-gyp',
gyp info spawn args   '-Dnode_lib_file=/Users/jaehonghan/Library/Caches/node-gyp/14.4.0/<(target_arch)/node.lib',
gyp info spawn args   '-Dmodule_root_dir=/Users/jaehonghan/dev/workspace_nodejs/first-react-app/node_modules/fsevents',
gyp info spawn args   '-Dnode_engine=v8',
gyp info spawn args   '--depth=.',
gyp info spawn args   '--no-parallel',
gyp info spawn args   '--generator-output',
gyp info spawn args   'build',
gyp info spawn args   '-Goutput_dir=.'
gyp info spawn args ]
No receipt for 'com.apple.pkg.CLTools_Executables' found at '/'.

No receipt for 'com.apple.pkg.DeveloperToolsCLILeo' found at '/'.

No receipt for 'com.apple.pkg.DeveloperToolsCLI' found at '/'.

gyp: No Xcode or CLT version detected!
gyp ERR! configure error 
gyp ERR! stack Error: `gyp` failed with exit code: 1
gyp ERR! stack     at ChildProcess.onCpExit (/usr/local/Cellar/node/14.4.0/libexec/lib/node_modules/npm/node_modules/node-gyp/lib/configure.js:351:16)
gyp ERR! stack     at ChildProcess.emit (events.js:315:20)
gyp ERR! stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:276:12)
gyp ERR! System Darwin 19.5.0
gyp ERR! command \"/usr/local/Cellar/node/14.4.0/bin/node\" \"/usr/local/Cellar/node/14.4.0/libexec/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js\" \"rebuild\"
gyp ERR! cwd /Users/jaehonghan/dev/workspace_nodejs/first-react-app/node_modules/fsevents
gyp ERR! node -v v14.4.0
success Saved lockfile.
success Saved 14 new dependencies.
info Direct dependencies
├─ cra-template@1.0.3
├─ react-dom@16.13.1
├─ react-scripts@3.4.1
└─ react@16.13.1
info All dependencies
├─ @babel/plugin-syntax-typescript@7.10.4
├─ @babel/plugin-transform-flow-strip-types@7.9.0
├─ @babel/plugin-transform-runtime@7.9.0
├─ @babel/plugin-transform-typescript@7.10.4
├─ @babel/preset-typescript@7.9.0
├─ babel-preset-react-app@9.1.2
├─ cra-template@1.0.3
├─ eslint-config-react-app@5.2.1
├─ react-dev-utils@10.2.1
├─ react-dom@16.13.1
├─ react-error-overlay@6.0.7
├─ react-scripts@3.4.1
├─ react@16.13.1
└─ scheduler@0.19.1
✨  Done in 11.28s.

Initialized a git repository.

Installing template dependencies using yarnpkg...
yarn add v1.22.4
[1/4] 🔍  Resolving packages...
warning @testing-library/react > @types/testing-library__react > @types/testing-library__dom@7.5.0: This is a stub types definition. testing-library__dom provides its own type definitions, so you do not need this installed.
[2/4] 🚚  Fetching packages...
[3/4] 🔗  Linking dependencies...
warning "react-scripts > @typescript-eslint/eslint-plugin > tsutils@3.17.1" has unmet peer dependency "typescript@>=2.8.0 || >= 3.2.0-dev || >= 3.3.0-dev || >= 3.4.0-dev || >= 3.5.0-dev || >= 3.6.0-dev || >= 3.6.0-beta || >= 3.7.0-dev || >= 3.7.0-beta".
warning " > @testing-library/user-event@7.2.1" has unmet peer dependency "@testing-library/dom@>=5".
[4/4] 🔨  Building fresh packages...
warning Error running install script for optional dependency: "/Users/jaehonghan/dev/workspace_nodejs/first-react-app/node_modules/fsevents: Command failed.
Exit code: 1
Command: node-gyp rebuild
Arguments: 
Directory: /Users/jaehonghan/dev/workspace_nodejs/first-react-app/node_modules/fsevents
Output:
gyp info it worked if it ends with ok
gyp info using node-gyp@5.1.0
gyp info using node@14.4.0 | darwin | x64
gyp info find Python using Python version 2.7.16 found at \"/System/Library/Frameworks/Python.framework/Versions/2.7/Resources/Python.app/Contents/MacOS/Python\"
gyp info spawn /System/Library/Frameworks/Python.framework/Versions/2.7/Resources/Python.app/Contents/MacOS/Python
gyp info spawn args [
gyp info spawn args   '/usr/local/Cellar/node/14.4.0/libexec/lib/node_modules/npm/node_modules/node-gyp/gyp/gyp_main.py',
gyp info spawn args   'binding.gyp',
gyp info spawn args   '-f',
gyp info spawn args   'make',
gyp info spawn args   '-I',
gyp info spawn args   '/Users/jaehonghan/dev/workspace_nodejs/first-react-app/node_modules/fsevents/build/config.gypi',
gyp info spawn args   '-I',
gyp info spawn args   '/usr/local/Cellar/node/14.4.0/libexec/lib/node_modules/npm/node_modules/node-gyp/addon.gypi',
gyp info spawn args   '-I',
gyp info spawn args   '/Users/jaehonghan/Library/Caches/node-gyp/14.4.0/include/node/common.gypi',
gyp info spawn args   '-Dlibrary=shared_library',
gyp info spawn args   '-Dvisibility=default',
gyp info spawn args   '-Dnode_root_dir=/Users/jaehonghan/Library/Caches/node-gyp/14.4.0',
gyp info spawn args   '-Dnode_gyp_dir=/usr/local/Cellar/node/14.4.0/libexec/lib/node_modules/npm/node_modules/node-gyp',
gyp info spawn args   '-Dnode_lib_file=/Users/jaehonghan/Library/Caches/node-gyp/14.4.0/<(target_arch)/node.lib',
gyp info spawn args   '-Dmodule_root_dir=/Users/jaehonghan/dev/workspace_nodejs/first-react-app/node_modules/fsevents',
gyp info spawn args   '-Dnode_engine=v8',
gyp info spawn args   '--depth=.',
gyp info spawn args   '--no-parallel',
gyp info spawn args   '--generator-output',
gyp info spawn args   'build',
gyp info spawn args   '-Goutput_dir=.'
gyp info spawn args ]
No receipt for 'com.apple.pkg.CLTools_Executables' found at '/'.

No receipt for 'com.apple.pkg.DeveloperToolsCLILeo' found at '/'.

No receipt for 'com.apple.pkg.DeveloperToolsCLI' found at '/'.

gyp: No Xcode or CLT version detected!
gyp ERR! configure error 
gyp ERR! stack Error: `gyp` failed with exit code: 1
gyp ERR! stack     at ChildProcess.onCpExit (/usr/local/Cellar/node/14.4.0/libexec/lib/node_modules/npm/node_modules/node-gyp/lib/configure.js:351:16)
gyp ERR! stack     at ChildProcess.emit (events.js:315:20)
gyp ERR! stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:276:12)
gyp ERR! System Darwin 19.5.0
gyp ERR! command \"/usr/local/Cellar/node/14.4.0/bin/node\" \"/usr/local/Cellar/node/14.4.0/libexec/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js\" \"rebuild\"
gyp ERR! cwd /Users/jaehonghan/dev/workspace_nodejs/first-react-app/node_modules/fsevents
gyp ERR! node -v v14.4.0
gyp ERR! node-gyp -v v5.1.0
gyp ERR! not ok"
info This module is OPTIONAL, you can safely ignore this error
success Saved lockfile.
success Saved 21 new dependencies.
info Direct dependencies
├─ @testing-library/jest-dom@4.2.4
├─ @testing-library/react@9.5.0
├─ @testing-library/user-event@7.2.1
├─ react-dom@16.13.1
└─ react@16.13.1
info All dependencies
├─ @babel/runtime-corejs3@7.10.4
├─ @sheerun/mutationobserver-shim@0.3.3
├─ @testing-library/dom@6.16.0
├─ @testing-library/jest-dom@4.2.4
├─ @testing-library/react@9.5.0
├─ @testing-library/user-event@7.2.1
├─ @types/prop-types@15.7.3
├─ @types/react-dom@16.9.8
├─ @types/react@16.9.41
├─ @types/testing-library__dom@7.5.0
├─ @types/testing-library__react@9.1.3
├─ aria-query@4.2.2
├─ css.escape@1.5.1
├─ csstype@2.6.10
├─ dom-accessibility-api@0.3.0
├─ min-indent@1.0.1
├─ react-dom@16.13.1
├─ react@16.13.1
├─ redent@3.0.0
├─ strip-indent@3.0.0
└─ wait-for-expect@3.0.2
✨  Done in 6.09s.
Removing template package using yarnpkg...

yarn remove v1.22.4
[1/2] 🗑  Removing module cra-template...
[2/2] 🔨  Regenerating lockfile and installing missing dependencies...
warning " > @testing-library/user-event@7.2.1" has unmet peer dependency "@testing-library/dom@>=5".
warning "react-scripts > @typescript-eslint/eslint-plugin > tsutils@3.17.1" has unmet peer dependency "typescript@>=2.8.0 || >= 3.2.0-dev || >= 3.3.0-dev || >= 3.4.0-dev || >= 3.5.0-dev || >= 3.6.0-dev || >= 3.6.0-beta || >= 3.7.0-dev || >= 3.7.0-beta".
[-/4] ⢀ waiting...
[2/4] ⢀ fsevents
[-/4] ⢀ waiting...
warning Error running install script for optional dependency: "/Users/jaehonghan/dev/workspace_nodejs/first-react-app/node_modules/fsevents: Command failed.
Exit code: 1
Command: node-gyp rebuild
Arguments: 
Directory: /Users/jaehonghan/dev/workspace_nodejs/first-react-app/node_modules/fsevents
Output:
gyp info it worked if it ends with ok
gyp info using node-gyp@5.1.0
gyp info using node@14.4.0 | darwin | x64
gyp info find Python using Python version 2.7.16 found at \"/System/Library/Frameworks/Python.framework/Versions/2.7/Resources/Python.app/Contents/MacOS/Python\"
gyp info spawn /System/Library/Frameworks/Python.framework/Versions/2.7/Resources/Python.app/Contents/MacOS/Python
gyp info spawn args [
gyp info spawn args   '/usr/local/Cellar/node/14.4.0/libexec/lib/node_modules/npm/node_modules/node-gyp/gyp/gyp_main.py',
gyp info spawn args   'binding.gyp',
gyp info spawn args   '-f',
gyp info spawn args   'make',
gyp info spawn args   '-I',
gyp info spawn args   '/Users/jaehonghan/dev/workspace_nodejs/first-react-app/node_modules/fsevents/build/config.gypi',
gyp info spawn args   '-I',
gyp info spawn args   '/usr/local/Cellar/node/14.4.0/libexec/lib/node_modules/npm/node_modules/node-gyp/addon.gypi',
gyp info spawn args   '-I',
gyp info spawn args   '/Users/jaehonghan/Library/Caches/node-gyp/14.4.0/include/node/common.gypi',
gyp info spawn args   '-Dlibrary=shared_library',
gyp info spawn args   '-Dvisibility=default',
gyp info spawn args   '-Dnode_root_dir=/Users/jaehonghan/Library/Caches/node-gyp/14.4.0',
gyp info spawn args   '-Dnode_gyp_dir=/usr/local/Cellar/node/14.4.0/libexec/lib/node_modules/npm/node_modules/node-gyp',
gyp info spawn args   '-Dnode_lib_file=/Users/jaehonghan/Library/Caches/node-gyp/14.4.0/<(target_arch)/node.lib',
gyp info spawn args   '-Dmodule_root_dir=/Users/jaehonghan/dev/workspace_nodejs/first-react-app/node_modules/fsevents',
gyp info spawn args   '-Dnode_engine=v8',
gyp info spawn args   '--depth=.',
gyp info spawn args   '--no-parallel',
gyp info spawn args   '--generator-output',
gyp info spawn args   'build',
gyp info spawn args   '-Goutput_dir=.'
gyp info spawn args ]
No receipt for 'com.apple.pkg.CLTools_Executables' found at '/'.

No receipt for 'com.apple.pkg.DeveloperToolsCLILeo' found at '/'.

No receipt for 'com.apple.pkg.DeveloperToolsCLI' found at '/'.

gyp: No Xcode or CLT version detected!
gyp ERR! configure error 
gyp ERR! stack Error: `gyp` failed with exit code: 1
gyp ERR! stack     at ChildProcess.onCpExit (/usr/local/Cellar/node/14.4.0/libexec/lib/node_modules/npm/node_modules/node-gyp/lib/configure.js:351:16)
gyp ERR! stack     at ChildProcess.emit (events.js:315:20)
gyp ERR! stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:276:12)
gyp ERR! System Darwin 19.5.0
gyp ERR! command \"/usr/local/Cellar/node/14.4.0/bin/node\" \"/usr/local/Cellar/node/14.4.0/libexec/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js\" \"rebuild\"
gyp ERR! cwd /Users/jaehonghan/dev/workspace_nodejs/first-react-app/node_modules/fsevents
gyp ERR! node -v v14.4.0
success Uninstalled packages.
✨  Done in 5.94s.

Created git commit.

Success! Created first-react-app at /Users/jaehonghan/dev/workspace_nodejs/first-react-app
Inside that directory, you can run several commands:

  yarn start
    Starts the development server.

  yarn build
    Bundles the app into static files for production.

  yarn test
    Starts the test runner.

  yarn eject
    Removes this tool and copies build dependencies, configuration files
    and scripts into the app directory. If you do this, you can’t go back!

We suggest that you begin by typing:

  cd first-react-app
  yarn start

Happy hacking!

 

npm start 또는 yarn start

브라우저 창에 http://localhost:3000/로 접속하시면 에 react 초기 페이지 나타납니다.

 

$ yarn start

$ yarn start

........


Compiled successfully!

You can now view first-react-app in the browser.

  Local:            http://localhost:3000
  On Your Network:  http://192.168.0.54:3000

Note that the development build is not optimized.
To create a production build, use yarn build.

 

http://localhost:3000/

 

728x90

참고URL

https://codinghub.tistory.com/39

 


Babel 
ECMAScript6를 지원하지 않는 환경에서 ECMAScript6 Syntax를 사용할 수 있게 해줍니다.

Webpack
모듈 번들러입니다.
Browserify 처럼 브라우저 위에서 import(require)을 할 수 있게 해주고 자바스크립트 파일들을 하나로 묶어 줍니다.

webpack-dev-server
webpack에서 지원하는 간단한 개발서버로써 별도의 서버를 구축하지 않아도 웹서버를 열 수 있으며 hot-loader 를 통하여 코드가 수정될때마다 자동으로 리로드되게 할 수 있습니다.


프로젝트를 위한 폴더 생성 및 npm 초기화 - 폴더명 myFristApp

$ mkdir myFirstApp
$ cd  myFirstApp
$ npm init

$ npm init

This utility will walk you through creating a package.json file.

It only covers the most common items, and tries to guess sensible defaults.



See `npm help json` for definitive documentation on these fields

and exactly what they do.



Use `npm install <pkg>` afterwards to install a package and

save it as a dependency in the package.json file.



Press ^C at any time to quit.

package name: (reactjs) 

version: (1.0.0) 

description: 

entry point: (index.js) 

test command: 

git repository: 

keywords: 

author: 

license: (ISC) 

About to write to /Users/jaehonghan/dev/workspace_nodejs/reactjs/package.json:



{

  "name": "reactjs",

  "version": "1.0.0",

  "description": "",

  "main": "index.js",

  "scripts": {

    "test": "echo \"Error: no test specified\" && exit 1"

  },

  "author": "",

  "license": "ISC"

}



Is this OK? (yes) 

 

package.json에 webpack-dev-server 스크립트 추가

package.json에 "dev-server":"webpack-dev-server" 추가해야 합니다.

추후 개발 서버를 실행하기 위해서 필요합니다.

 

$ vi package.json

{
  "name": "reactjs",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "dev-server":"webpack-dev-server" 
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "babel-cli": "^6.26.0",
    "babel-core": "^6.26.3",
    "babel-loader": "^8.1.0",
    "babel-polyfill": "^6.26.0",
    "babel-preset-env": "^1.7.0",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-react": "^6.24.1",
    "babel-preset-react-hmre": "^1.1.1",
    "babel-preset-stage-0": "^6.24.1",
    "css-loader": "^3.6.0",
    "file-loader": "^6.0.0",
    "node-sass": "^4.14.1",
    "react": "^16.13.1",
    "react-dom": "^16.13.1",
    "react-hot-loader": "^4.12.21",
    "sass-loader": "^8.0.2",
    "style-loader": "^1.2.1",
    "url-loader": "^4.1.0",
    "webpack": "^4.43.0",
    "webpack-dev-middleware": "^3.7.2",
    "webpack-dev-server": "^3.11.0",
    "webpack-hot-middleware": "^2.25.0"
  },
  "dependencies": {
    "bootstrap": "^4.5.0",
    "react-bootstrap": "^1.0.1"
  }
}

 

리엑트 설치

$ npm install --save-dev react react-dom

$ npm install --save-dev react react-dom


npm notice created a lockfile as package-lock.json. You should commit this file.

npm WARN reactjs@1.0.0 No description

npm WARN reactjs@1.0.0 No repository field.



+ react-dom@16.13.1

+ react@16.13.1

added 8 packages from 3 contributors and audited 8 packages in 0.695s

found 0 vulnerabilities

 

부트스트랩 설치

$ npm install --save bootstrap react-bootstrap

$ npm install --save bootstrap react-bootstrap

npm WARN bootstrap@4.5.0 requires a peer of jquery@1.9.1 - 3 but none is installed. You must install peer dependencies yourself.

npm WARN bootstrap@4.5.0 requires a peer of popper.js@^1.16.0 but none is installed. You must install peer dependencies yourself.

npm WARN reactjs@1.0.0 No description

npm WARN reactjs@1.0.0 No repository field.



+ react-bootstrap@1.0.1

+ bootstrap@4.5.0

added 22 packages from 43 contributors and audited 30 packages in 2.929s



2 packages are looking for funding

  run `npm fund` for details



found 0 vulnerabilities

 

css /  sass 설치

$ npm install --save-dev sass-loader css-loader style-loader node-sass

$ npm install --save-dev sass-loader css-loader style-loader node-sass

npm WARN deprecated request@2.88.2: request has been deprecated, see https://github.com/request/request/issues/3142



> node-sass@4.14.1 install /Users/jaehonghan/dev/workspace_nodejs/reactjs/node_modules/node-sass

> node scripts/install.js



Downloading binary from https://github.com/sass/node-sass/releases/download/v4.14.1/darwin-x64-83_binding.node

Download complete░░⸩ ⠋ :

Binary saved to /Users/jaehonghan/dev/workspace_nodejs/reactjs/node_modules/node-sass/vendor/darwin-x64-83/binding.node

Caching binary to /Users/jaehonghan/.npm/node-sass/4.14.1/darwin-x64-83_binding.node



> node-sass@4.14.1 postinstall /Users/jaehonghan/dev/workspace_nodejs/reactjs/node_modules/node-sass

> node scripts/build.js



Binary found at /Users/jaehonghan/dev/workspace_nodejs/reactjs/node_modules/node-sass/vendor/darwin-x64-83/binding.node

Testing binary

Binary is fine

npm WARN bootstrap@4.5.0 requires a peer of jquery@1.9.1 - 3 but none is installed. You must install peer dependencies yourself.

npm WARN bootstrap@4.5.0 requires a peer of popper.js@^1.16.0 but none is installed. You must install peer dependencies yourself.

npm WARN sass-loader@8.0.2 requires a peer of webpack@^4.36.0 || ^5.0.0 but none is installed. You must install peer dependencies yourself.

npm WARN css-loader@3.6.0 requires a peer of webpack@^4.0.0 || ^5.0.0 but none is installed. You must install peer dependencies yourself.

npm WARN style-loader@1.2.1 requires a peer of webpack@^4.0.0 || ^5.0.0 but none is installed. You must install peer dependencies yourself.

npm WARN reactjs@1.0.0 No description

npm WARN reactjs@1.0.0 No repository field.



+ sass-loader@8.0.2

+ css-loader@3.6.0

+ node-sass@4.14.1

+ style-loader@1.2.1

added 224 packages from 177 contributors and audited 254 packages in 9.398s



11 packages are looking for funding

  run `npm fund` for details



found 0 vulnerabilities

 

 

Babel 설치

$ npm install --save-dev babel-core babel-loader babel-cli babel-preset-react babel-preset-es2015 babel-preset-stage-0 babel-polyfill babel-preset-env file-loader url-loader babel-preset-react-hmre

$ npm install --save-dev babel-core babel-loader babel-cli babel-preset-react babel-preset-es2015 babel-preset-stage-0 babel-polyfill babel-preset-env file-loader url-loader babel-preset-react-hmre



npm WARN deprecated babel-preset-es2015@6.24.1: 🙌  Thanks for using Babel: we recommend using babel-preset-env now: please read https://babeljs.io/env to update!

npm WARN deprecated chokidar@1.7.0: Chokidar 2 will break on node v14+. Upgrade to chokidar 3 with 15x less dependencies.

npm WARN deprecated core-js@2.6.11: core-js@<3 is no longer maintained and not recommended for usage due to the number of issues. Please, upgrade your dependencies to the actual version of core-js@3.

npm WARN deprecated fsevents@1.2.13: fsevents 1 will break on node v14+ and could be using insecure binaries. Upgrade to fsevents 2.

npm WARN deprecated resolve-url@0.2.1: https://github.com/lydell/resolve-url#deprecated

npm WARN deprecated urix@0.1.0: Please see https://github.com/lydell/urix#deprecated



> fsevents@1.2.13 install /Users/jaehonghan/dev/workspace_nodejs/reactjs/node_modules/fsevents

> node install.js



No receipt for 'com.apple.pkg.CLTools_Executables' found at '/'.



No receipt for 'com.apple.pkg.DeveloperToolsCLILeo' found at '/'.



No receipt for 'com.apple.pkg.DeveloperToolsCLI' found at '/'.



gyp: No Xcode or CLT version detected!

gyp ERR! configure error 

gyp ERR! stack Error: `gyp` failed with exit code: 1

gyp ERR! stack     at ChildProcess.onCpExit (/usr/local/lib/node_modules/npm/node_modules/node-gyp/lib/configure.js:351:16)

gyp ERR! stack     at ChildProcess.emit (events.js:315:20)

gyp ERR! stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:276:12)

gyp ERR! System Darwin 19.5.0

gyp ERR! command "/usr/local/Cellar/node/14.4.0/bin/node" "/usr/local/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js" "rebuild"

gyp ERR! cwd /Users/jaehonghan/dev/workspace_nodejs/reactjs/node_modules/fsevents

gyp ERR! node -v v14.4.0

gyp ERR! node-gyp -v v5.1.0

gyp ERR! not ok 



> core-js@2.6.11 postinstall /Users/jaehonghan/dev/workspace_nodejs/reactjs/node_modules/core-js

> node -e "try{require('./postinstall')}catch(e){}"



Thank you for using core-js ( https://github.com/zloirock/core-js ) for polyfilling JavaScript standard library!



The project needs your help! Please consider supporting of core-js on Open Collective or Patreon: 

> https://opencollective.com/core-js 

> https://www.patreon.com/zloirock 



Also, the author of core-js ( https://github.com/zloirock ) is looking for a good job -)



npm WARN bootstrap@4.5.0 requires a peer of jquery@1.9.1 - 3 but none is installed. You must install peer dependencies yourself.

npm WARN bootstrap@4.5.0 requires a peer of popper.js@^1.16.0 but none is installed. You must install peer dependencies yourself.

npm WARN css-loader@3.6.0 requires a peer of webpack@^4.0.0 || ^5.0.0 but none is installed. You must install peer dependencies yourself.

npm WARN sass-loader@8.0.2 requires a peer of webpack@^4.36.0 || ^5.0.0 but none is installed. You must install peer dependencies yourself.

npm WARN style-loader@1.2.1 requires a peer of webpack@^4.0.0 || ^5.0.0 but none is installed. You must install peer dependencies yourself.

npm WARN babel-loader@8.1.0 requires a peer of @babel/core@^7.0.0 but none is installed. You must install peer dependencies yourself.

npm WARN babel-loader@8.1.0 requires a peer of webpack@>=2 but none is installed. You must install peer dependencies yourself.

npm WARN file-loader@6.0.0 requires a peer of webpack@^4.0.0 || ^5.0.0 but none is installed. You must install peer dependencies yourself.

npm WARN url-loader@4.1.0 requires a peer of webpack@^4.0.0 || ^5.0.0 but none is installed. You must install peer dependencies yourself.

npm WARN reactjs@1.0.0 No description

npm WARN reactjs@1.0.0 No repository field.



+ babel-loader@8.1.0

+ babel-preset-env@1.7.0

+ babel-polyfill@6.26.0

+ babel-cli@6.26.0

+ babel-preset-react@6.24.1

+ babel-core@6.26.3

+ babel-preset-stage-0@6.24.1

+ file-loader@6.0.0

+ url-loader@4.1.0

+ babel-preset-react-hmre@1.1.1

+ babel-preset-es2015@6.24.1

added 314 packages from 130 contributors and audited 569 packages in 38.757s



13 packages are looking for funding

  run `npm fund` for details



found 1 low severity vulnerability

  run `npm audit fix` to fix them, or `npm audit` for details

 

.babelrc  파일 생성

$ vi .babelrc

{
   "presets":["env","react","es2015", "stage-0"],
   "env":{
      "development":{
         "presets":["react-hmre"]
      }
   }
}

 

WebPack 설치

$ npm install --save-dev react-hot-loader webpack webpack-dev-server webpack-dev-middleware webpack-hot-middleware 

$ npm install --save-dev react-hot-loader webpack webpack-dev-server webpack-dev-middleware webpack-hot-middleware 



npm WARN deprecated chokidar@2.1.8: Chokidar 2 will break on node v14+. Upgrade to chokidar 3 with 15x less dependencies.

npm WARN notsup Unsupported engine for watchpack-chokidar2@2.0.0: wanted: {"node":"<8.10.0"} (current: {"node":"14.4.0","npm":"6.14.4"})

npm WARN notsup Not compatible with your version of node/npm: watchpack-chokidar2@2.0.0

npm WARN babel-loader@8.1.0 requires a peer of @babel/core@^7.0.0 but none is installed. You must install peer dependencies yourself.

npm WARN bootstrap@4.5.0 requires a peer of jquery@1.9.1 - 3 but none is installed. You must install peer dependencies yourself.

npm WARN bootstrap@4.5.0 requires a peer of popper.js@^1.16.0 but none is installed. You must install peer dependencies yourself.

npm WARN reactjs@1.0.0 No description

npm WARN reactjs@1.0.0 No repository field.



+ webpack-dev-middleware@3.7.2

+ webpack-hot-middleware@2.25.0

+ react-hot-loader@4.12.21

+ webpack-dev-server@3.11.0

+ webpack@4.43.0

added 463 packages from 312 contributors and audited 1033 packages in 10.309s



31 packages are looking for funding

  run `npm fund` for details



found 1 low severity vulnerability

  run `npm audit fix` to fix them, or `npm audit` for details

 

 

webpack 설정 -  webpack.config.js

프로젝트 폴더에 webpack 설정파일인 webpack.config.js 을 생성하고 아래의 내용을 입력합니다.

var webpack = require('webpack');

var path = require('path');

module.exports = {

  entry: [

    'webpack-hot-middleware/client',

    './src/index.js'

  ],

  output: {

    path: __dirname + '/public/',

    filename: 'bundle.js'

  },

  devServer: {

    hot: true,

    inline: true,

    port: 4000,

    contentBase: __dirname + '/public/',

  },

  module: {

      loaders: [

        {

          test: /\.js$/,

          loaders: ['react-hot-loader', 'babel-loader'],

          include: path.join(__dirname, 'src')

        },

        {

          test: /\.less$/,

          loader: 'style-loader!css-loader!less-loader'  // use ! to chain loaders

        },

        {

          test: /\.css$/,

          loader: 'style-loader!css-loader'

        },

        {

          test: /\.scss$/,

          loader: 'style-loader!css-loader!sass-loader'

        },

        {

          test: /\.(png|jpg)$/,

          loader: 'url-loader?limit=8192' // inline base64 URLs for <=8k images, direct URLs for the rest

        }

      ]

  },

  plugins: [ new webpack.HotModuleReplacementPlugin() ]

}

react app 만들기

1. 처음에 생성한 myFirstApp 에 public, src 폴더를 생성합니다.

webpack.config.js에서 개발 서버가 바라볼 기본 폴더는 public가 됩니다.

$ cd myFirstApp
$ mkdir public
$ mkdir src

 

2. public 폴더에 index.html 파일을 아래와 같이 생성합니다.

$ cd public/index.html

-- index.html에 간략한 내용 입력

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>React App with Babel + webpack</title>
  </head>

  <body>
    <div id="contents"></div>
    <script src="bundle.js"></script>
  </body>
</html>

 

3. src 폴더에 components 폴더를 생성합니다.

src 폴더의 하위에 components  폴더를 만들고 src/components Contents.react.js 파일을 생성하고 아래의 내용을 입력합니다.

$ cd ../src
$ mkdir components
$ vi Contents.react.js


-- Contents.react.js 파일의 내용

import React from 'react';
class Contents extends React.Component {
  render() {
    return ( <h1>React + Webpack + Babel First Apps</h1> );
  }
}

 

4. 개발 서버를 실행합니다.

브라우저에서 http://localhost:4000에 접속하시면 결과를 확인할 수 있습니다.

$ cd myFirstApp
$ npm run dev-server

+ Recent posts