728x90
728x90

 

🌲공식문서

 

시작하기 | Vue.js

시작하기 NOTE 이미 Vue 2를 알고 있고 Vue 3의 새로운 점을 배우고 싶으신가요? Migration Guide를 확인하세요! Vue.js가 무엇인가요? Vue(/vjuː/ 로 발음, view 와 발음이 같습니다.)는 사용자 인터페이스를

v3.ko.vuejs.org

 

🌲Installation

🌳CDN방식

HTML에 Script소스코드를 삽입해 사용하는 방법

See the Pen Untitled by kim so wol (@siot0) on CodePen.

 

 

 

 

🌳CLI방식

터미널에서 전역으로 설치하는 방법

$ npm i -g @vue/cli

 

🌵Vue 명령어로 새로운 프로젝트 생성하기

1. vue create 폴더명

$ vue create hello-vue

 

2. 생성이 완료되면 Vue 버전 선택

 

3. 기본 명령어

cd hello-vue : 디렉토리가 hello-vue로 생성되었고

npm run serve : serve라는 키워드로 개발자모드를 열 수 있다.

*vulnerabilities취약점이 14개나 발견되었다는데 왜때문인지 모르겠네

 

4. 새로 생성한 프로젝트를 불러오면

*vue cli는 기본적으로 webpack번들러를 사용

*lint

 

(package.json)

{
  "name": "hello-vue",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "serve": "vue-cli-service serve",
    "build": "vue-cli-service build",
    "lint": "vue-cli-service lint"
  },
  "dependencies": {
    "core-js": "^3.6.5",
    "vue": "^3.0.0"
  },
  "devDependencies": {
    "@vue/cli-plugin-babel": "~4.5.0",
    "@vue/cli-plugin-eslint": "~4.5.0",
    "@vue/cli-service": "~4.5.0",
    "@vue/compiler-sfc": "^3.0.0",
    "babel-eslint": "^10.1.0",
    "eslint": "^6.7.2",
    "eslint-plugin-vue": "^7.0.0"
  },
  "eslintConfig": {
    "root": true,
    "env": {
      "node": true
    },
    "extends": [
      "plugin:vue/vue3-essential",
      "eslint:recommended"
    ],
    "parserOptions": {
      "parser": "babel-eslint"
    },
    "rules": {}
  },
  "browserslist": [
    "> 1%",
    "last 2 versions",
    "not dead"
  ]
}

 

🌵Vue CLI 공식문서

 

Vue CLI

 

cli.vuejs.org

 

 

 

 


🌲Webpack template

🌳installation

1. 기본적인 vue 문법해석 설치

$ npm i vue@next

*@next : 최신 버전으로 설치

 

2. 관련 패키지 설치

vue-style-loader : vue파일의 style태그를 해석

@vue/compiler-sfc : 브라우저에서 vue파일이 작동하도록 변환

$ npm i -D vue-loader@next vue-style-loader @vue/compiler-sfc

 

3. webpack.config.js에서 module과 plugins 추가

const { VueLoaderPlugin } = require('vue-loader')

module: {
    rules: [
      { test: /\.vue&/, use: 'vue-loader' },
      {
        test: /\.s?css$/,
        use: [ 'vue-style-loader', 'style-loader', 'css-loader', 'postcss-loader', 'sass-loader' ]
      }
   
plugins: [ new VueloaderPlugin() ]

 

 

🌳import

1. main.js파일에서 vue파일 연결하기 (html에서도 #app부분 삽입 필요)

import { createApp } from 'vue'
import App from './App'

createApp(App).mount('#app')

 

🌵 resolve.extensions

js파일에서 확장자없이 import하는 webpack.config.js옵션

module.exports = {
   resolve: {
    extensions: ['.js', '.vue']
   }

 

 

🌳components

1. 경로 별칭이란?

지칭하는 경로로 바로 점핑

 

1-1. file-loader

이미지파일과 같은 특정한 파일을 읽어 브라우저에서 동작시키는 패키지 설치 필요

$ npm i -D file-loader

 

// webpack.config.js

module: {
    rules: [
      {
        test: /\.(png|jpe?g|gif|webp|svg)$/,
        use: 'file-loader'
      }
    ]
  },

 

1-2. 경로 별칭 사용법

alias옵션에서 원하는 이름(~ 또는 assets)에 해당 경로를 지정하여 사용할 수 있다.

module.exports = {
   resolve: {
    extensions: ['.js', '.vue'],
    alias: {
      '~': path.resolve(__dirname, 'src'),
      'assets': path.resolve(__dirname, 'src/assets')
    }

 

  <img src="~assets/favicon.png" alt="">

 

🌵components

HelloWorld란 이름으로 컴포넌츠 만들어 사용하는 예시

// App.vue

<template>
  <h1>{{ message }}</h1>
  <HelloWorld />
</template>

<script>
import HelloWorld from '~/components/HelloWorld'

export default {
  components: {
    HelloWorld
  },
  data() {
    return {
      message: 'Hello!!'
    }
  }
}
</script>

 

 


🌲vuejs의 반응성

🌵 Vue.js의 구성

SFC(Single file Component) 단일 파일 컴포넌트는 template, script, style로 구성되어 있다.

template는 html, script는 js, style는 css(scss)를 작성한다. template, script에서는 vue문법으로 작성한다.

 

 

🌲반복문과 조건문

디렉티브 v-를 이용해 표현

🌳반복문

fruits 배열 안에 있는 데이터 수만큼 반복하여 fruit를 list형태로 배열

<template>
  <ul>
    <Fruit 
    v-if="fruit in fruits" 
    :key="fruit"
    :name="fruit">
      {{ fruit }}
    </Fruit>
  </ul>
</template>


<script>
export default {
  data() {
    return {
      fruits: [ 'Apple', 'Banana', 'Cherry']
    }
  }
</script>

 

 

🌳조건문

count의 기본값 0에서 시작하여 h1을 클릭할 때마다 1씩 증가, count가 4보다 커지면 '4보다 크다'

<template>
  <h1 @click="increase">{{ count }}</h1>
  <div v-if="count > 4"> 
    4보다 크다 
  </div>
</template>

<script>
export default {
  data() {
    return {
      count: 0
  },
  methods: {
    increase: function () {
      this.count += 1
    }
  }
}
</script>

 

 

 


🌲vetur

vue코드의 하이라이팅을 만드는 VScode 확장프로그램

 

728x90
728x90

🌲ESLint

ESLint란? 에크마스크립트의 코드규칙에 vue를 도입하여 사용하는 문법구성인데 구체적인 코딩스타일을 지정하여 협업 시 통일된 코드스타일을 유지할 수 있다.

🌵vue eslint 공식문서

 

User Guide | eslint-plugin-vue

User Guide 💿 Installation Via vue-cli (Recommended): Via npm (opens new window): Via yarn (opens new window): Requirements ESLint v6.2.0 and above Node.js v12.22.x, v14.17.x, v16.x and above 📖 Usage Configuration Use .eslintrc.* file to configure rul

eslint.vuejs.org

 

🌳 설치

$ npm i -D eslint eslint-plugin-vue babel-eslint

 

🌳 .eslintrc.js

module.exports = { 
  env: { 
    browser: true, 
    node: true }, 
  extends: [ 
    'plugin:vue/vue3-strongly-recommended', 
    'eslint:recommended' 
  ], 
  parserOptions: { 
    parser: 'babel-eslint' }, 
    rules: { 
      "vue/html-closing-bracket-newline": ["error", { 
        "singleline": "never",
        "multiline": "always" 
      }], 
      "vue/html-self-closing": ["error", { 
        "html": { 
          "void": "always", 
          "normal": "never", 
          "component": "always" 
        }, 
        "svg": "always", 
        "math": "always" 
     }] 
  } 
}
module.exports 속성값의 객체 또는 배열 설명 상세설명
env browser: boolean browser 브라우저 환경에서 검사
node: boolean nodejs 노드 환경에서 검사
extends plugin:vue/vue3-essential
plugin:vue/vue3-strongly-recommended
plugin:vue/vue3-recommended
vue 설정 Lv 1
Lv 2
Lv 3 가장 엄격
eslint:recommended js 설정 권장하는 기본 규칙
parseroptions parser: 'babel-eslint' babel 구버전에서도 동작
rules 권장 규칙 이외에 추가할 때 사용
vue/html-closing-bracket-newline "singleline": "never" >를 newline에 쓰지 않음(never)
"multiline": "always" 다중라인에서는 >를 newline에 사용함(always)
vue/html-self-closing "void": "always" 빈 태그에 닫힘 /를 사용함(always)
"normal": "never" div와 같은 태그에 닫힘/를 사용안 함(never)
"component": "always" 컴포넌트 태그에 닫힘/를 사용함

 

🌳 자동수정 저장

VSCODE에서 자동수정 후 저장하는 설정을 추가할 수 있다. ESLint문법에 맞지 않게 작성했더라도 파일 저장 시 알아서 문법에 맞게 변경되어 수정이 된다.

VScode에서 ctrl+shit+P를 눌러 모든 명령 표시 검색창에서 settings를 검색하면  


기본 설정: 설정 열기(JSON)으로 들어가 다음 코드를 추가한다.

"editor.codeActionsOnSave": { "source.fixAll.eslint": true }

 

🌵Eslint rules 공식문서

 

List of available rules

✓no-unreachabledisallow unreachable code after `return`, `throw`, `continue`, and `break` statements

eslint.org

 

728x90
728x90

npx로 프로젝트 다운받기

📌 버전 관리가 없는 새로운 프로젝트를 다운로드 받는 것과 같다.

 

npx degit 계정이름/저장소이름 다운받을경로

$ npx degit kim-siot/repositoryname directory

*npx : degit을 설치하지 않고도 사용할 수 있는 nodejs명령어 npx

*degit : 원격저장소 github에 있는 특정 저장소를 현재 로컬 경로에 다운로드

 

 

git clone으로 프로젝트 복제하기

git저장소에서 직접 다운로드 받을 때는 버전까지 한꺼번에 다운되어 프로젝트를 이어서 진행하게 된다.

 

 

728x90
728x90
 

🌲webpack


install


webpack과 cli(커맨드 라인 인터페이스 지원) 그리고 cli버전과 맞추기 위해 @next로 설치

*webpack-dev-server는 webpack-cli가 선행되어야 자동가능하다.

npm i webpack webpack-cli webpack-dev-server@next

 

scripts

package.json


webpack 개발모드(--mode development)와 제품 모드(--mode production) 설정

  "scripts": {
   "dev": "webpack-dev-server --mode development",
   "build": "webpack --mode production"
  },

 

config

webpack.config.js


parcel-bundler는 기본옵션이 제공되나 webpack은 직접 구성 옵션을 설정해줘야 한다. 규모있는 프로젝트에서 세세한 설정을 지정해 활용하기 좋다. webpack.config.js는 브라우저 환경이 아닌 node.js환경에서 작동한다. 

parcel에서의 import,export와 비슷한 개념으로 이해하면 쉬운데 entry는 경로를 불러들이는 진입점, ouput은 이 결과물을 반환하는 절대경로에 관련된 설정을 말한다.

추가로 플러그인을 설치한 후 이 파일에서 상세 옵션을 지정해준다. (지금부터 나올 플러그인들 모두 이 파일을 거쳐간다.)

 

const path = require('path')

module.exports = {
  entry: './js/main.js',
  output: {
    // path: path.resolve(__dirname, 'dist'),
    // filename: 'main.js',
    clean: true
  }
}

-> ./js/main.js에서 불러들인 내용을 번들하여 dist폴더에 main.js라는 이름으로 결과물을 반환

 

entry ./js/main.js 경로를 불러들이는 진입점
output.path const path = require('path')
path.resolve(__dirname, 'dist')
결과물(번들)을 반환하는 절대경로
output.filename main.js 결과물 파일명
output.clean true 기존에 생성된 디렉토리 제거, clean옵션을 사용하지 않으면 디렉토리명과 파일명을 새로 지정할 때마다 새로이 생성된다.

*output.path와 outputfilename을 설정해주지 않아도 기본적으로 dist디렉토리에 entry파일명 그대로 생성된다.

*dirname은 해당하는 파일의 실제 경로를 나타내는 nodejs의 전역 변수

 

 

🌍 plugin

번들링 후 결과물의 처리 방식 등 다양한 플러그인들을 설정


html-webpack-plugin

html파일을 템플릿으로 생성할 수 있게 도와주는 플러그인이다. html파일에 link,script로 css,js을 연결하지 않아도 파일을 자동으로 읽어 html파일을 빌드할 수 있게 해준다. (결과적으로 dist폴더 내에 들어가게 된다.) 컴파일이나 번들링 등 빌드된 파일 이름에 해시가 포함된 경우 유용하다.

npm i -D html-webpack-plugin

1 webpack.config.js

const path = require('path')
const HtmlPlugin = require('html-webpack-plugin')

module.exports = {
   entry: './js/main.js',
    output: {
    // path: path.resolve(__dirname, 'dist'),
    // filename: 'main.js',
    clean: true
  },

  // 번들링 후 결과물의 처리 방식 등 다양한 플러그인들을 설정
  plugins: [
    new HtmlPlugin({
      template: './index.html'
    })
  ],

  devServer: {
    host: 'localhost'
  }
}

 

copy-webpack-plugin

디렉토리를 카피하여 dist에 들어갈 수 있도록 설정하는 플러그인이다.

이미지, 파비콘과 같은 정적 파일은 하나의 디렉토리에 넣어 빌드하면 편하다. 

npm i -D copy-webpack-plugin

1 webpack.config.js

const CopyPlugin = require('copy-webpack-plugin')
//
plugins: [
    new HtmlPlugin({
      template: './index.html'
    }),
    new CopyPlugin({
      patterns: [
        { from: 'static' } // static폴더로부터
      ]
    })
  ],

 

CSS와 SCSS

css-loader, style-loader, sass-loader, sass

css-loader : js파일에서 css파일을 불러들이도록 도와주는 플러그인

style-loader : html파일의 style안 으로 css를 삽입해주는 역할

sass-loader : js파일에서 scss파일을 불러들이도록 도와주는 플러그인

npm i -D css-loader style-loader
npm i -D sass-loader sass

1 webpack.config.js

  module: {
    rules: [
      {
        test: /\.s?css$/, // scss혹은 css확장자 파일 찾기
        use: [
          'style-loader', // 작성 순서가 중요
          'css-loader',
          'sass-loader'
        ]
      }
    ]
  }

2 main.js

import '../scss/main.scss'

*module은 css, scss, babel등을 불러읽어 들어올 수 있도록 webpack-loader설정을 추가해주는 부분이다.

 

 

postcss, autoprefixer, loader

postcss(스타일에 후처리를 도와주는 패키지)를 사용하여 autoprefixer(공급업체접두사를 자동으로 붙여주는 플러그인)을 사용, webpack에서 postcss를 동작하게 해주는 postcss-loader

npm i -D postcss autoprefixer postcss-loader

1 webpack.config.js

*작성 순서 중요

module: {
    rules: [
      {
        test: /\.s?css$/,
        use: [  'style-loader', 'css-loader', 'postcss-loader', 'sass-loader' ]
      }
    ]
  },

2 package.json

autoprefixer를 사용할 때는 browserslist를 꼭 작성해줘야 함

  "browserslist": [
    "> 1%",
    "last 2 versions"
  ]

3 .postcssrc.js

module.exports = {
  plugins: [
    require('autoprefixer')
  ]
}

 

babel

npm i -D @babel/core @babel/preset-env @babel/plugin-transform-runtime babel-loader

1 webpack.config.js

        test: /\.js$/,
        use: [
          'babel-loader'

2 .babelrc.js

module.exports = { 
  presets: ['@babel/preset-env'], 
  plugins: [ 
    ['@babel/plugin-transform-runtime'] 
  ] 
}

 

 

build 결과

dist폴더 내에 연결된 파일들이 불러들여와진다.

 

 

 


webpack.config.js 전체 내용

const path = require('path')
const HtmlPlugin = require('html-webpack-plugin')
const CopyPlugin = require('copy-webpack-plugin')

module.exports = {
   entry: './js/main.js',
    output: {
    // path: path.resolve(__dirname, 'dist'),
    // filename: 'main.js',
    clean: true
  },

  module: {
    rules: [
      {
        test: /\.s?css$/,
        use: [ 'style-loader', 'css-loader', 'postcss-loader', 'sass-loader' ]
      },
      {
        test: /\.js$/,
        use: [ 'babel-loader' ]
      }
    ]
  },

  plugins: [
    new HtmlPlugin({
      template: './index.html'
    }),
    new CopyPlugin({
      patterns: [
        { from: 'static' }
      ]
    })
  ],

  devServer: {
    host: 'localhost'
  }
}

 

728x90
728x90
 

 


Parcel


1. 컴파일러

scss 등의 파일을 자동 컴파일하는 기능

2. 브라우저

로컬환경에서 브라우저 연결 

3. 정적파일 복붙 📌

dist폴더에 자동 연결하는 플러그인 parcel-plugin-static-files-copy

$ npm i -D parcel-plugin-static-files-copy
 

parcel-plugin-static-files-copy

ParcelJS plugin to copy static files from static dir to bundle directory.

www.npmjs.com

staticFiles 옵션

-> "static"이라는 이름의 폴더를 parcel패키지가 dist폴더로 복붙한다.

*개발서버에서는 dist폴더 내에 있는 index.html이 작동한다. favicon과 같은 파일은 dist폴더 내에 index.html파일 근처에 있어야 하기 때문에 파일 이동이 불가피한데 이때 dist폴더에 그냥 넣으면 dist파일은 언제든지 삭제될 수 있으며 gitignore대상이 될 수 있어 리스크가 크다. static files copy 플러그인은 말그대로 이미지와 같은 정적 파일들을 복사 붙여넣기 해주는 기능이다. 옵션에서 지정한 폴더(여기서는 static)에 해당 파일을 옮겨 담으면 원본은 static폴더 안에서 보존되면서 dist파일에는 자동 붙여넣기가 된다.

 

 


autoprefixer📌


공급 업체 접두사 Vender Prefix를 자동으로 붙여주는 모듈 postcss, autoprefixer

표준이 아닌 구형브라우저에서 적용가능하도록 webkit, ms 등 공급 업체의 접두사를 붙이는데 이 기능을 대신 해주는 플러그인이다.

$ npm i -D postcss autoprefixer

 

browserslist📌


npm프로젝트에서 지원할 브라우저의 범위를 명시하는 용도로 autoprefixer패키지가 이 옵션을 활용하게 된다.

-> 전세계 점유율이 1% 이상인 모든 브라우저에 한해서 최근 2버전까지 지원함을 의미

 

.postcssrc.js📌


◽ 파일 이름 설명

  • 뒤에 rc(Runtime Configuration)가 붙은 파일 : 구성 파일
  • 파일이름 앞에 .마침표가 붙는 파일 : 구성 옵션 또는 숨김 파일

 .postcssrc.js파일은 commonjs 방식으로 작성

브라우저에서 사용하지 않고 번들러로 변환하는 용도로만 사용하기 때문에 nodejs 환경에서 동작하기 때문에 commonjs방식을 사용한다.

  • ESM : ECMAScript Module 방식 -> import와 export
  • commonjs 방식 -> require()함수와 module.exports
// import autoprefixer from 'autoprefixer'
const autoprefixer = require('autoprefixer')

// export {
//   plugins: [
//     autoprefixer
//   ]
// }
module.exports = {
  plugins: [
    autoprefixer
  ]
}

코드를 더 줄여서 변수없이 사용

module.exports = {
  plugins: [
    require('autoprefixer')
  ]
}

-> 제대로 잘 작동하는지 알아보려면 css파일에 display:flex(최신기술)를 적용했을 때 아래 그림과 같이 나온다.

 

 


Babel 📌

최신 문법으로 작성한 것을 구형브라우저에서도 잘 작동하도록 예전 문법으로 변환


ECMAScript 2015+ (ES6) 이상 코드를 이전 js 엔진에서 실행할 수 있는 이전 버전과 호환되는 js 버전으로 변환하는 데 사용되는 js 트랜스 컴파일러

 

설치

$ npm i -D @babel/core @babel/preset-env

 

.babelrc.js

새 파일 .bablerc.js에 commonjs방식으로 작성

module.exports = {
  presets: ['@babel/preset-env']
}

 

package.json

autoprefixer와 마찬가지로 package.json파일에서 browserslist옵션을 추가해줘야 한다.

-> 전세계 점유율이 1% 이상인 모든 브라우저에 한해서 최근 2버전까지 지원함을 의미

 

transform-runtime

async await 키워드(비동기 문법)를 사용할 수 있게끔 해주는 플러그인

$ npm i -D @babel/plugin-transform-runtime

 

.babelrc.js

위 플러그인 관련 옵션 추가

module.exports = {
  presets: ['@babel/preset-env'],
  plugins: [
    ['@babel/plugin-transform-runtime']
  ]
}

 

 


CLI

command line interface : 터미널 명령어


 

🖥 커맨드 라인 인터페이스(CLI)

시작하기 기능 📦 애셋 유형 고급 🖥 커맨드 라인 인터페이스(CLI) 명령어 Serve 개발용 서버를 시작합니다. 앱이 수정되면 자동으로 다시 빌드하고, 빠른 개발을 위해 빠른 모듈 교체를 지원합니

ko.parceljs.org

개발용, 제품용으로 구분해서 사용

728x90

'FE' 카테고리의 다른 글

NPX degit과 git clone의 차이점  (0) 2021.12.05
번들러 webpack 플러그인 사용법  (0) 2021.12.05
Bootstrap 부트스트랩 UI 프레임워크  (0) 2021.11.28
git the requested URL returend error : 403  (0) 2021.11.28
goorm IDE  (0) 2021.11.28
+ Recent posts
728x90