본문으로 건너뛰기

Full Stack JavaScript Developer | Half-time Open Sourcerer.

모든 저자 보기

Git 원격 저장소 생성 및 SSH 인증 - Github 포함

· 약 1분

Git 원격 저장소 생성

서버에서 실행

## 서버에 로그인 후 원하는 위치에서 폴더를 만든다.
$ mkdir [이름].git

## 해당 폴더로 이동한다.
$ cd [이름].git

## Git 원격 저장소를 초기화한다.
$ git init --bare

SSH 생성

클라이언트에서 실행

Email 인증 방식

Github 인증을 하려면 이 방식을 이용해야한다.

## 키 발급
$ ssh-keygen -t rsa -C "[email protected]"

## 클라이언트에 이메일 키 추가
$ eval "$(ssh-agent -s)"
$ ssh-add ~/.ssh/id_rsa

사용자 인증 방식

## 키 발급
$ ssh-keygen -t rsa

SSH 폴더로 이동해 인증키 복사

클라이언트에서 실행

$ cd ~/.ssh
$ vi id_rsa.pub

## id_rsa.pub의 내용을 복사한다.

인증키 등록

일반 서버

서버에서 실행

## ssh 폴더로 이동
$ cd ~/.ssh

## 인증키 파일을 연다.
$ vi authorized_keys

## id_rsa.pub에서 복사된 인증키를 하단에 추가한다.

Github

Github에서 실행

Email-인증-방식 으로 인증키를 생성해야하고 이메일은 github 에 로그인하는 이메일과 같아야한다

키 등록

github 에 로그인 후 설정에 가서 복사한 키를 등록한다. image from hexo

인증여부 확인

클라이언트에서 실행

## 등록 후 에 클라이언트에서 인증여부를 확인한다.

## You've successfully authenticated 가 보이면 인증완료

Git Repositiory 초기화

클라이언트에서 실행

$ git clone 서버유저명@서버아이피:[이름].git
## ex ) git clone [email protected]:test.git

hexo image tag의 alt 속성 사용

· 약 1분

공식 문서에 따르면 image tag 의 사용법은 이렇다.

![image from hexo]([class names] /path/to/image [width] [height] [title text
[alt text]])

대괄호로 둘러 쌓인 부분은 생략이 가능하다.

문제점

Input

test.png 에 test_title, test_alt 속성을 추가하고 싶은 경우 아래처럼 사용하면 되어야한다.

![image from hexo](/test.png test_title test_alt)

Output

하지만 결과는 참담하다.

<img src="/test.png" title="test_title test_alt" />

해결

Input

속성을 quotes 와 double quotes 로 두번 감싸줘야한다.

![image from hexo](/test.png "'test_title'" "'test_alt'")

Output

<img src="/test.png" title="test_title" alt="test_alt" />

여담

공식 문서에 설명이 업데이트되면 좋겠다. 이미지에 캡션다는 법을 찾다가 결국 내 블로그에는 안 달기로 마음먹었다.

Web Server for Chrome - 가장 빨리 웹서버 구동하기

· 약 1분

github의 예제 프로젝트나 라이브러리를 받을 때, 데모를 실행시키고 싶을 때가 있다. 그럴려면 node나 apache, nginx, iis 등의 웹서버에서 해당 폴더를 설정하고, hosts파일에서 열어줘야하는 번거로움이 있다.

Web Server for Chrome을 사용하면 몇 초 안으로 데모를 띄울 수 있다.

설치

image from hexo

  1. 크롬 설치 후 웹스토어 접속
  2. 검색란에서 Web Server for Chrome 검색
  3. 설치

사용법

Web Server 실행

image from hexo chrome://apps/에 접속 후 Web Server 아이콘을 클릭한다.

설정 및 구동

image from hexo Automatically show index.html 설정을 체크한 후 CHOOSE FOLDER로 웹서버를 돌릴 폴더를 선택해주자. 그리고 127.0.0.1:8887 (또는 localhost:8887)로 접속하면 끝!

여담

Html과 Javascript로 나만의 UI를 만들고 빠르게 확인하는데 좋을 것 같다. Service Worker 같은 Https가 필요한 기술도 실행이 가능하다.

Detecting AdBlock

· 약 1분

Google Analytics, Facebook Pixel, Naver Analytics 등의 분석 스크립트 및 Google Adsence 를 차단하는 AdBlock 을 감지해보자

소스

/**
@author https://www.christianheilmann.com/2015/12/25/detecting-adblock-without-an-extra-http-overhead/
*/
(function (adBlockEnabled) {
"use strict";
const testAd = document.createElement("div");
testAd.innerHTML = "&nbsp;";
testAd.className = "adsbox";
document.body.appendChild(testAd);

setTimeout(function () {
if (testAd.offsetHeight === 0) {
adBlockEnabled = true;
}
testAd.remove();

if (adBlockEnabled) {
alert(
"This Blog is made possible by displaying online advertisements\nPlease consider by disabling your ad blocker",
);
}
}, 100);
})((window.adBlockEnabled = window.adBlockEnabled || false));

출처의 소스를 즉시실행함수로 변경하고, 문구를 추가했다.

설명

AdBlock 에 의해 차단되는 영역인 .adsbox div 의 생성유무를 확인해 AdBlock 의 adBlockEnabled 변수의 값을 정한다.

uBlock 도 잘 찾아낸다.

jQuery Change Class

· 약 1분

Toggle Event 사용시 AAA 로 명명된 클래스를 BBB 로 바꾸고 싶을 때가 있다.

$("#id").removeClass("AAA").addClass("BBB");

보통 이런 방식으로 사용하는데, alterClass 함수를 곁들이면 더 나이스하게 바꿀 수 있다.

소스

/**
@author https://gist.github.com/peteboere/1517285
*/
$.fn.alterClass = function (removals, additions) {
if (removals.indexOf("*") === -1) {
// Use native jQuery methods if there is no wildcard matching
this.removeClass(removals);
return !additions ? this : this.addClass(additions);
}

const pattern = new RegExp(
"\\s" +
removals.replace(/\*/g, "[A-Za-z0-9-_]+").split(" ").join("\\s|\\s") +
"\\s",
"g",
);

this.each(function (i, it) {
let cn = " " + it.className + " ";
while (pattern.test(cn)) {
cn = cn.replace(pattern, " ");
}
it.className = $.trim(cn);
});

return !additions ? this : this.addClass(additions);
};

예제

// AAA to BBB
$("#id").alterClass("AAA", "BBB");
// AAA-12, BBB-13 to AAABBB
$("#id").alterClass("AAA-* BBB-*", "AAABBB");

**asterisk(*)**를 이용해 여러 개의 클래스를 한꺼번에 원하는 클래스로 변경할 수 있다.

여담

jQuery UI 를 사용 중이라면, .switchClass를 사용하면 된다.

jQuery serializeObject - form을 json으로 변환

· 약 1분

비동기 submit 을 진행시에 form 값을 확인해보고 json object 로 받아 한 번에 request 를 날리고 싶을 때 유용하다.

소스

/*
@author https://github.com/macek/jquery-serialize-object
*/
$.fn.serializeObject = function () {
"use strict";
const result = {};
const extend = function (i, element) {
const node = result[element.name];
if ("undefined" !== typeof node && node !== null) {
if ($.isArray(node)) {
node.push(element.value);
} else {
result[element.name] = [node, element.value];
}
} else {
result[element.name] = element.value;
}
};

$.each(this.serializeArray(), extend);
return result;
};

예제

const formData = $("#form").serializeObject();

여담

checkbox 같은 경우 여러 개 선택시 하나의 key 에 배열로 반환된다.

<form>
<input type="checkbox" name="arr" value="1" checked />
<input type="checkbox" name="arr" value="2" checked />
</form>

<script>
var formData = $("form").serializeObject();
// => formData = { arr : [1,2] };
</script>

사실 이 기능이 제일 매력적이다.

현재 serializeObject library는 더 높은 버전이 있다. 최신 버전에선 form 의 name 속성에 object 를 직접 관리할 수 있다. 최신 버전을 써도 괜찮고, 가볍게 추가해서 쓰고 싶으면 위 버전을 이용하자.

jQuery Enter Event

· 약 1분

로그인 폼을 만들 때 tab 과 enter 를 이용해 로그인 할 수 있게 해줘야한다.

소스

$("#id").keypress(function (e) {
if (e.which === 13) {
// do something
}
});

여담

로그인 폼을 매번 만들지 않기 때문에, e.which 는 매번 헷갈린다..

git add 안 되는 경우 확인해야될 것

· 약 2분

git add . 명령어 실행 후에 commit -m 명령어 실행 시, 또는 git commit -am 명령어로 바로 커밋시 add 가 되지 않은 것처럼 빨간 파일이 보일 경우

add 확인

git add .
git add path_to_submodule

두 명령어를 다시 실행해본다.

diff 확인

그래도 add 가 안 되는 경우 diff 를 먼저 실행해본다.

git diff
git diff path_to_submodule

dirty diff 가 있을 경우

submodule 종속 제거

내 프로젝트 안에 git clone 으로 가져온 library 가 있는지 확인해보자.

git submodule foreach --recursive git checkout .

모듈이 없다는 결과가 나올 경우

  • git 에서 가져온 library 를 모두 확인하고
  • .git 폴더가 생성되어있으면 삭제

모듈 결과가 있는 경우

  • .gitmodule 파일의 해당 모듈 부분 삭제
  • git add .gitmodules
  • .git/config 파일의 해당 모듈 부분 삭제
  • git rm --cached path_to_submodule 캐시 삭제
  • rm -rf .git/modules/path_to_submodule 모듈 폴더 삭제
  • git commit -m "Removed submodule {name}" 모듈 종속 삭제를 커밋하고
  • rm -rf path_to_submodule 모듈 파일 모두 삭제

없는 경우

cached 파일 제거

git rm -r --cached .
git rm -r --cached path_to_submodule

untracked 파일 제거

git clean -d -x -f

-d 는 디렉토리 포함, -x 는 ignored 파일 포함, -f === force

commit 으로 초기화

git reset --hard

이 명령어는 마지막 방법이 되어야한다. 작업량을 다 날릴 수 있다.

여담

git 버전이 높아지면서 프로젝트 내에 git 에 종속적인 모듈이 있으면 add 자체가 안 된다. path_to_submodule 은 submodule 의 상대경로, 즉 add 가 안 되는 파일의 경로를 적으면 된다.

jQuery Opener Document 제어

· 약 1분

pure javascript

부모창을 제어하는 구문은 아래처럼 사용한다.

document.parent.getElementById("id");
window.opener.document.getElementById("id");

jQuery

jQuery를 사용하고 있다면 생각보다 쉽게 요소 선택을 할 수 있다.

const $id = $("#id", opener.document); // parent.document도 가능
$id.val("value");

2열처럼 바로 값 변경도 가능하다.

form.reset()의 input hidden 초기화 문제

· 약 1분

Javascript 의 form 의 reset() 메소드는 hidden field 와 check, radio button 에 대해 초기화를 시켜주지 않는다.

따라서 form 의 모든 field 를 초기화 시키려면 아래의 메소드가 필요하다.

소스

$.fn.clearForm = function () {
return this.each(function () {
const type = this.type,
tag = this.tagName.toLowerCase();
if (tag === "form") {
return $(":input", this).clearForm();
}
if (
type === "text" ||
type === "password" ||
type === "hidden" ||
tag === "textarea"
) {
this.value = "";
} else if (type === "checkbox" || type === "radio") {
this.checked = false;
} else if (tag === "select") {
this.selectedIndex = -1;
}
});
};

예제

$("#form").clearForm();

설명

여기의 clearForm 메소드를 hidden 도 초기화할 수 있게 커스터마이징 했다.