Find Unused JavaScript And CSS Code With The Coverage Tab In Chrome DevTools

Open the Coverage tab

  1. 커맨드 창 열기.
  2. coverage 를 커맨드 검색창에 입력하고, Show Coverage 를 선택한다. Coverage 탭이 개발자도구의 Drawer에 활성화된다.

Record code coverage

  1. Coverage 탭에서 아래에 따라 버튼을 클릭한다 :
    • 페이지를 로딩하기 위해서 어떤 코드들이 필요한지 보기 위해Start Instrumenting Coverage And Reload Page Start Instrumenting Coverage And Reload Page 를 클릭한다.
    • 페이지에서 어떤 코드들이 사용되는지 보기 위해 Instrument Coverage Instrument Coverage 을 클릭한다.
  2. 코드 커버리지 녹화 중단을 위해 Stop Instrumenting Coverage And Show Results Stop Instrumenting Coverage And Show Results 를 클릭한다.

Analyze code coverage

Coverage 탭은 각 리소스에서 얼마나 많은 코드가 사용되었는지, 분석 결과를 알려준다. 리소스의 각 행을 클릭하면 Sources 패널에서 사용되는 코드와 사용되지 않는 코드를 분리해서 확인할 수 있다.

  • URL 컬럼은 분석되는 리소스의 URL.
  • Type 컬럼은 리소스가 CSS, JavaScript 중 어떤 타입을 포함하고 있는지.
  • Total Bytes 컬럼은 리소스 파일의 크기.
  • Unused Bytes 컬럼은 사용되지 않는 리소스의 크기.
  • 마지막 이름없는 컬럼은 위의 Total BytesUnused Bytes 를 시각화 해놓은 것. 붉은 색은 미사용, 녹색은 사용하는 리소스의 크기를 나타냄.

CSS Reference

Select an element

  • 원하는 요소에서 우클릭 후 > Inspect
  • 개발자 도구에서 요소 선택 Select an
 element
  • Command+Shift+C (Mac) 또는 Control+Shift+C (Windows, Linux) 후 원하는 요소 선택
  • 개발자 도구의 DOM Tree에서 원하는 요소 선택
  • 개발자 도구 Console 에서 document.querySelector('p') 입력 > 콘솔 결과에서 우클릭 후 Reveal in Elements panel 클릭

View CSS

View the external stylesheet where a rule is defined

Styles 팬에서, CSS규칙 옆의 link를 클릭하면 외부 스타일 시트를 볼 수 있음. 만약, 스타일 시트가 minify 되어 있다면, minified file 보는 법을 참조

View only the CSS that's actually applied to an element

  1. 요소 선택
  2. Elements 패널의 Computed 탭에 가면 선택 요소에 실제 적용되는 css규칙만 확인할 수 있음.
  • 상속된 css를 모두 확인하려면 Show All 체크박스를 클릭

View CSS properties in alphabetical order

Computed탭을 이용

View inherited CSS properties

ComputedShow All 체크박스를 선택

View an element's box model

Styles 탭 제일 하단에 Box Model 다이어그램을 통해 확인 가능하고, 조정 원하는 값을 더블클릭하고 변경 가능

Search and filter an element's CSS

StylesComputedFilter 텍스트 박스를 통해 원하는 css규칙 검색 또는 필터링 가능

Toggle a pseudo-class

  1. 요소 선택
  2. Elements 패널의 Styles 탭으로 이동
  3. :hov 클릭
  4. 원하는 가상 선택자 클릭

View a page in print mode

  1. Command Menu를 열고
  2. Rendering을 타이핑하고 Show Rendering를 선택
  3. Emulate CSS Media 드랍다운 상자에서, print를 선택

View used and unused CSS with the Coverage tab

  1. 개발자 도구를 열고 > Command+Shift+P (Mac) 또는 Control+Shift+P (Windows, Linux, Chrome OS)
  2. coverage을 타이핑하고 Show Coverage를 클릭하면 Coverage 탭이 생김
  3. Start Instrumenting Coverage And Reload Page Start Instrumenting Coverage
And Reload Page 를 클릭. 페이지를 다시 읽어오면 브라우저가 읽어오는 각 파일의css 또는 javascript 정보가 얼마나 많이 이용되는지 요약 정보를 제공함. 녹색은 사용하는 css를 붉은색은 사용하지 않는 css를 나타냄.
  4. 표시되는 각 파일을 클릭하면 줄바꿈이 된 상세정보 확인 가능

Force print preview mode

Force DevTools Into Print Preview Mode.

Change CSS

Add a CSS declaration to an element

Add an inline declaration

  1. 요소 선택
  2. Styles팬에서, element.style 중괄호 사이를 선택.
  3. 원하는 속성명과 값을 입력
  4. DOM Tree에서 style 속성이 적용된 것을 확인

Add a declaration to a style rule

  1. 요소 선택
  2. Styles 팬에서, 원하는 추가를 원하는 곳을 선택.
  3. 속성명과 값을 입력

Change a declaration name or value

더블클릭에서 속성명과 값을 바꿀 수 있음.

Change declaration values with keyboard shortcuts

  • 0.1단위 증가 : Option+Up (Mac) / Alt+Up (Windows, Linux)
  • 10단위 증가 : Shift+Up
  • 100단위 증가 : Shift+Command+Up (Mac) / Shift+Page Up (Windows, Linux)

Add a class to an element

  1. DOM Tree에서 요소 선택
  2. .cls 클릭
  3. Add New Class 텍스트 상자에 클래스 이름 입력

Toggle a class

  1. DOM Tree에서 요소 선택
  2. Add New Class 아래에 요소에 적용되는 모든 클래스 표시
  3. 체크박스를 토글

Add a style rule

  1. 요소를 선택
  2. New Style Rule New Style Rule를 클릭 > element.style 아래에 새로운 규칙이 추가.

Toggle a declaration

Change colors with the Color Picker

  1. 요소선택
  2. Styles 탭에서, 변경을 원하는 color 또는 background-color 선언을 찾는다. color 또는 background-color 값 옆에 색을 미리보여주는 네모 박스를 찾는다.
  3. 색 미리보기 네모를 클릭하면 Color Picker가 활성화된다.

Change angle value with the Angle Clock

  1. 요소 선택
  2. Styles 탭에서, 변경을 원하는transform 또는 background 선언을 찾는다. 각도 값 옆에 Angle Preview 박스를 클릭한다.
  3. Angle Clock 미리보기를
  4. Angle Clock 을 클릭 또는 스크롤해서 값을 조정한다.

출처 :크롬 개발자도구 공식 가이드

Get Started With Viewing And Changing CSS

View an element's CSS

  • 원하는 요소 위에서 우클릭 > Inspect

Add a CSS declaration to an element

  • Styles tab > element.style 선택한 요소에 원하는 css 입력

Add a CSS class to an element

  • Styles tab > :cls 클릭하고 원하는 class 입력
  • 체크 버튼으로 클래스 활성/비활성 선택 가능

Add a pseudostate to a class

  • Styles tab > :hov 클릭하고 원하는 요소에 가상 상태 부여 가능

Change the dimensions of an element

  • Box Model 다이어그램에서 넓이, 높이, 패딩, 마진, 선 두께등을 조절할 수 있음

출처 :크롬 개발자도구 공식 가이드

Open the Elements panel to inspect the DOM or CSS

Open the Elements panel to inspect the DOM or CSS

  • 크롬 빈화면 우클릭 -> inspect
  • Command+Option+C (Mac)
  • Control+Shift+C (Windows, Linux, Chrome OS)

Open the Console panel to view logged messages or run JavaScript

  • Command+Option+J (Mac)
  • Control+Shift+J (Windows, Linux, Chrome OS)

Open the last panel you had open

  • Press Command+Option+I (Mac)
  • Control+Shift+I

Open DevTools from Chrome's main menu

  • More Tools > Developer Tools.

Auto-open DevTools on every new tab

/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --auto-open-devtools-for-tabs

출처:크롬 개발자도구 공식 가이드

Maven으로 자바 프로젝트 빌드하기

프로젝트 셋팅

디렉터리 구조

mkdir -p src/main/java/hello를 통해서 기본 디렉터리 생성

src/main/java/hello/HelloWorld.java

package hello;

public class HelloWorld {
  public static void main(String[] args) {
  Greeter greeter = new Greeter();
  System.out.println(greeter.sayHello());
  }
}

src/main/java/hello/Greeter.java

package hello;

public class Greeter {
  public String sayHello() {
  return "Hello world!";
  }
}

메이븐 설치

메이븐 공식에서 직접 다운로드 후 설치
설치 후, terminal에서 정상 설치 확인

메이븐 정상 설치 확인

mvn -v

메이븐 기본 구조 정의

프로젝트의 root위치에 아래의 pom.xml 파일 생성.

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.springframework</groupId>
    <artifactId>gs-maven</artifactId>
    <packaging>jar</packaging>
    <version>0.1.0</version>

    <properties>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-shade-plugin</artifactId>
                <version>3.2.4</version>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>shade</goal>
                        </goals>
                        <configuration>
                            <transformers>
                                <transformer
                                    implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                                    <mainClass>hello.HelloWorld</mainClass>
                                </transformer>
                            </transformers>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>
  • modelVersion - POM model version (always 4.0.0).
  • groupId - 프로젝트가 소속된 그룹, 조직의 id. (도메인 네임 역순으로 표현 많이 함.)
  • artifactId - JAR 또는 WAR로 빌드될 이름.
  • version - 프로젝트의 버전.
  • packaging - 프로젝트의 패키징 형태. 기본이 Jar, 필요시 War로 변경.

자바 파일 빌드

mvn compile
//target/classes 디렉터리에 .class파일로 compile 결과 생성.

mvn package
//compile -> test -> target 폴더에 jar파일 생성.

mvn install
//compile -> test -> 로컬 레포지토리에 패키지를 배포.
//package와의 차이점 ? 로컬 레포지토리에 패키지를 생성해서, 로컬에 있는 다른 프로젝트들이 접근이 가능하다는 차이가 있음. 

의존성 선언

src/main/java/hello/HelloWorld.java

현재 시간을 표시하기 위해 LocalTime 외부 메소드를 사용.

package hello;

import org.joda.time.LocalTime;

public class HelloWorld {
  public static void main(String[] args) {
    LocalTime currentTime = new LocalTime();
    System.out.println("The current local time is: " + currentTime);
    Greeter greeter = new Greeter();
    System.out.println(greeter.sayHello());
  }
}

위 HelloWorld.java 파일을 정상 빌드 되게 하기 위해서 pom.xml에 아래의 의존성 추가.

<dependencies>
        <dependency>
            <groupId>joda-time</groupId>
            <artifactId>joda-time</artifactId>
            <version>2.9.2</version>
        </dependency>
</dependencies>
  • groupId - 라이브러리가 소속된 그룹, 조직 id.
  • artifactId - 라이브러리의 id.
  • version - 라이브러리의 버전.

Scope

  • compile - 미입력시에도 기본 적용. 컴파일시 필요한 의존성. (WAR 파일 빌드 시 파일의 /WEB-INF/libs폴더에 포함됨.)
  • provided - 컴파일 시 필요하지만, 실행환경에서는 컨테이너에 의해 제공 될 의존성(ex> the Java Servlet API)
    provided로 지정 시 마지막 패키징할 때 포함되지 않음.
  • test - 컴파일과 테스트시에만 사용되고 프로젝트 실행시에는 불필요한 의존성.

Test 작성

Junit 추가

<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
    <scope>test</scope>
</dependency>

src/test/java/hello/GreeterTest.java

package hello;

import static org.hamcrest.CoreMatchers.containsString;
import static org.junit.Assert.*;

import org.junit.Test;

public class GreeterTest {

  private Greeter greeter = new Greeter();

  @Test
  public void greeterSaysHello() {
    assertThat(greeter.sayHello(), containsString("Hello"));
  }

}
mvn test
//src/test/java 아래에 *Test와 매칭되는 테스트들을 실행.

mvn install
//test 태스크를 포함한 라이프사이클 실행.

최종 pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.springframework</groupId>
    <artifactId>gs-maven</artifactId>
    <packaging>jar</packaging>
    <version>0.1.0</version>

    <properties>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>

    <dependencies>
        <!-- tag::joda[] -->
        <dependency>
            <groupId>joda-time</groupId>
            <artifactId>joda-time</artifactId>
            <version>2.9.2</version>
        </dependency>
        <!-- end::joda[] -->
        <!-- tag::junit[] -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <!-- end::junit[] -->
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-shade-plugin</artifactId>
                <version>3.2.4</version>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>shade</goal>
                        </goals>
                        <configuration>
                            <transformers>
                                <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                                    <mainClass>hello.HelloWorld</mainClass>
                                </transformer>
                            </transformers>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>

출처 : https://spring.io/guides/gs/maven/

'공식메뉴얼 > spring.io' 카테고리의 다른 글

Building Java Projects with Gradle  (0) 2020.10.31
Consuming a RESTful Web Service  (0) 2020.10.31
Scheduling Tasks  (0) 2020.09.06
Building a RESTful Web Service  (0) 2020.09.06

Grale로 자바 프로젝트 빌드하기

프로젝트 셋팅

디렉터리 구조

mkdir -p src/main/java/hello를 통해서 기본 디렉터리 생성

HelloWorld.java

package hello;

public class HelloWorld {
  public static void main(String[] args) {
  Greeter greeter = new Greeter();
  System.out.println(greeter.sayHello());
  }
}

Greeter.java

package hello;

public class Greeter {
  public String sayHello() {
  return "Hello world!";
  }
}

그레이들 설치

  • SDKMAN
  • Homebrew (brew install gradle)
    중 택하여 그레이들을 로컬 피씨에 설치하거나 https://www.gradle.org/downloads 에서 직접 다운로드

그레이들 기능 확인

gradle tasks

그레이들로 자바 빌드하기

build.gradle 에 java 플러그인 추가

...
apply plugin: 'java'
...

터미널에 그레이들 빌드 명령어 입력

gradle build

빌드가 성공적으로 종료시 build아래 다음과 같은 폴더들이 생성된 것을 확인할 수 있음.

  • classes : 컴파일된 .class 파일

  • reports : 빌드에 의해 생성된 리포트들 (ex>테스트 결과 보고서)

  • libs : 프로젝트 라이브러리들 모음. (ex>jar/war)

의존성 선언

  • reositories에 라이브러리를 가져올 위치를 지정
  • 의존성 타입
    • compile : compile시에 필요한 dependency를 설정한다.
    • testCompile : test 시에 필요한 dependency를 설정한다.
    • providedCompile : compile시에는 필요하지만, 배포시에는 제외될 dependency를 설정한다. (war plugin이 설정된 경우에만 사용 가능하다)
    • providedRuntime : runtime시에만 필요하고, 실행환경에서 제공되는 dependency를 설정한다. (war plugin이 설정된 경우에만 사용 가능하다)
  • jar 영역에는 빌드될 jar파일의 정보를 기입 ex>gs-gradle-0.1.0.jar.

그레이들로 실행가능하도록 만들기

application 플러그인을 추가하고 메인클래스를 지정 gradle run으로 실행

  • war파일로 빌드하고 싶다면 war plugin 추가
  • spring boot 사용중이고 실행 가능한 jar파일로 빌드하고 싶다면 spring-boot-gradle-plugin 추가
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'application'

mainClassName = 'hello.HelloWorld'

// tag::repositories[]
repositories {
    mavenCentral()
}
// end::repositories[]

// tag::jar[]
jar {
    baseName = 'gs-gradle'
    version =  '0.1.0'
}
// end::jar[]

// tag::dependencies[]
sourceCompatibility = 1.8
targetCompatibility = 1.8

dependencies {
    compile "joda-time:joda-time:2.2"
    testCompile "junit:junit:4.12"
}
// end::dependencies[]

// tag::wrapper[]
// end::wrapper[]

Gradle Wrapper로 빌드하기

//래퍼 파일 생성
$ gradle wrapper --gradle-version 2.13

//래퍼로 빌드
./gradlew build

출처 : https://spring.io/guides/gs/gradle/

'공식메뉴얼 > spring.io' 카테고리의 다른 글

Building Java Projects with Maven  (0) 2020.11.15
Consuming a RESTful Web Service  (0) 2020.10.31
Scheduling Tasks  (0) 2020.09.06
Building a RESTful Web Service  (0) 2020.09.06

RESTful web services를 사용하는 서비스 만들기.

RESTful한 서비에스에서 응답받은 json형태를 곧바로 사용하기에는 불편함이 있음. 때문에 스프링의 RestTemplate 라이브러리를 이용해서 사용하기 편한 구조화된 객체 형태로 변환함.

build.gradle

plugins {
    id 'org.springframework.boot' version '2.1.7.RELEASE'
    id 'io.spring.dependency-management' version '1.0.8.RELEASE'
    id 'java'
}

group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'

repositories {
    mavenCentral()
}

dependencies {
    implementation 'org.springframework.boot:spring-boot-sta-brter-web'
    testImplementation 'org.springframework.boot:spring-boot-starter-test'
}

응답을 받은 데이터를 저장할 객체

  • @JsonIgnoreProperties(ignoreUnknown = true) 은 해당 타입에 없는 정보는 무시하기 위해 사용
  • @JsonProperty 은 json데이터 중에서 객체 필드에 직접 맵핑하고 싶은 것이 있을 때 사용 (현 예제는 넘어오는 json 키이름이 필드와 일치해서 미사용)

Quote.java

@JsonIgnoreProperties(ignoreUnknown = true)
public class Quote {

  private String type;
  private Value value;

  public Quote() {
  }

  public String getType() {
    return type;
  }

  public void setType(String type) {
    this.type = type;
  }

  public Value getValue() {
    return value;
  }

  public void setValue(Value value) {
    this.value = value;
  }

  @Override
  public String toString() {
    return "Quote{" +
        "type='" + type + '\'' +
        ", value=" + value +
        '}';
  }
}

Value.java

@JsonIgnoreProperties(ignoreUnknown = true)
public class Value {

  private Long id;
  private String quote;

  public Value() {
  }

  public Long getId() {
    return this.id;
  }

  public String getQuote() {
    return this.quote;
  }

  public void setId(Long id) {
    this.id = id;
  }

  public void setQuote(String quote) {
    this.quote = quote;
  }

  @Override
  public String toString() {
    return "Value{" +
        "id=" + id +
        ", quote='" + quote + '\'' +
        '}';
  }
}

SpringBoot 서비스를 구동

  • logger : 결과를 로그 창에 나타내기 위해 사용

  • RestTemplate : 호출한 데이터를 Jackson JSON 프로세스 라이브러리로 가공

  • CommandLineRunner : 어플리케이션 시작시 메소드를 구동

@SpringBootApplication
public class ConsumingRestApplication {

    private static final Logger log = LoggerFactory.getLogger(ConsumingRestApplication.class);

    public static void main(String[] args) {
        SpringApplication.run(ConsumingRestApplication.class, args);
    }

    @Bean
    public RestTemplate restTemplate(RestTemplateBuilder builder) {
        return builder.build();
    }

    @Bean
    public CommandLineRunner run(RestTemplate restTemplate) throws Exception {
        return args -> {
            Quote quote = restTemplate.getForObject(
                    "https://gturnquist-quoters.cfapps.io/api/random", Quote.class);
            log.info(quote.toString());
        };
    }
} 

출처 : https://spring.io/guides/gs/consuming-rest/

'공식메뉴얼 > spring.io' 카테고리의 다른 글

Building Java Projects with Maven  (0) 2020.11.15
Building Java Projects with Gradle  (0) 2020.10.31
Scheduling Tasks  (0) 2020.09.06
Building a RESTful Web Service  (0) 2020.09.06

스프링으로 테스크 스케쥴링 하기

1. gradle 셋팅

plugins {
    id 'org.springframework.boot' version '2.3.2.RELEASE'
    id 'io.spring.dependency-management' version '1.0.8.RELEASE'
    id 'java'
}

group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'

repositories {
    mavenCentral()
}

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter'
    testImplementation 'org.awaitility:awaitility:3.1.2'
    testImplementation('org.springframework.boot:spring-boot-starter-test') {
        exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
    }
}

test {
    useJUnitPlatform()
}

2. 스케쥴 테스크 생성

  • @Scheduled : 실행하고 싶은 특정 메소드 위에 @Scheduled 어노테이션을 붙임.
  • fixedRate : 호출의 시작 시간부터 메소드 호출 간격을 지정.
    (fixedDelay : 호출의 완료 시간부터 메소드 호출 간격을 지정. 상세 지정을 위해 cron = "..."식을 사용할 수도 있음.)
//ScheduledTasks.java
package com.example.schedulingtasks;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class ScheduledTasks {

    private static final Logger log = LoggerFactory.getLogger(ScheduledTasks.class);

    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");

    @Scheduled(fixedRate = 5000)
    public void reportCurrentTime() {
        log.info("The time is now {}", dateFormat.format(new Date()));
    }
}

3. 스케쥴 기능 활설화

  • @EnableScheduling 어노테이션은 백그라운드 태스크 실행기가 생성되도록 함. 없으면 작업 예약 기능(Scheduling)이 작동하지 않음.
package com.example.schedulingtasks;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;

@SpringBootApplication
@EnableScheduling
public class SchedulingTasksApplication {

    public static void main(String[] args) {
        SpringApplication.run(SchedulingTasksApplication.class);
    }
}

출처 : https://spring.io/guides/gs/scheduling-tasks/

'공식메뉴얼 > spring.io' 카테고리의 다른 글

Building Java Projects with Maven  (0) 2020.11.15
Building Java Projects with Gradle  (0) 2020.10.31
Consuming a RESTful Web Service  (0) 2020.10.31
Building a RESTful Web Service  (0) 2020.09.06

+ Recent posts