VanillaJS SPA Routing 구현

protect-me·2021년 6월 21일
0

⚙️ 환경구축


Terminal

$ npm init -y
$ npm i webpack webpack-cli webpack-dev-server -D
$ npm i clean-webpack-plugin css-loader handlebars handlebars-loader mini-css-extract-plugin html-webpack-plugin -D
  • npm 초기화
  • webpack 설치
  • clean-webpack-plugin - 빌드 결과물(dist)을 초기화
  • css-loader - css 사용을 위한 로더
  • handlebars - html template을 사용하기 위한 템플릿 엔진
  • handlebars-loader - webpack에서 handlebars를 사용하기 위한 로더
  • mini-css-extract-plugin - css 결과물을 내보내기 위한 플러그인
  • html-webpack-plugin - entryhtml에 동적 삽입과 html 결과물을 내보내기 위한 플러그인

webpack.config.js

const HtmlWebpackPlugin = require('html-webpack-plugin')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const { CleanWebpackPlugin } = require('clean-webpack-plugin')

const { resolve } = require('path')

module.exports = {
  entry: {
    router: './router.js',
    app: './index.js'
  },

  output: {
    path: resolve(__dirname, './dist'),
    filename: '[name].js'
  },

  plugins: [
    new HtmlWebpackPlugin({
      filename: 'index.html', // output file name
      template: 'index.html'  // template file name
    }),
    new MiniCssExtractPlugin({ filename: 'app.css' }),
    new CleanWebpackPlugin({
      cleanAfterEveryBuildPatterns: ['dist']
    })
  ],

  module: {
    rules: [
      {
        test: /\.hbs$/,
        loader: 'handlebars-loader'
      },
      {
        test: /\.css$/,
        use: [MiniCssExtractPlugin.loader, 'css-loader']
      }
    ]
  }
}

package.json

  • scripts 부분 수정
{
  "scripts": {
    "start": "webpack-dev-server",
    "build": "webpack --mode=production"
  }
}


index.html 및 각 페이지 생성

index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>spa-router-example</title>
</head>
<body>

<!--BrowserHistory-->
<div>
  <!--Link-->
  <div class="link-container">
    <div class="link-box">
      <span class="history" route="/about">History About</span>
    </div>

    <div class="link-box">
      <span class="history" route="/home">History Home</span>
    </div>
  </div>

  <!--Content-->
  <div id="history-app"></div>
</div>

<hr/>

<!--HashHistory-->
<div>
  <!--Link-->
  <div class="link-container">
    <div class="link-box">
      <a class="hash" href="#about">Hash About</a>
    </div>

    <div class="link-box">
      <a class="hash" href="#home">Hash Home</a>
    </div>
  </div>

  <!--Content-->
  <div id="hash-app"></div>
</div>
</body>
</html>


Error

Error: Cannot find module 'webpack-cli/bin/config-yargs'
webpack 과 webpack-dev-server 버전이 서로간 충돌로 인해서 아래와 같이 버전을 맞춰 주면 됩니다.
설치가 안되면 관리자 권한 sudo 를 통해 실행하시면 됩니다.

npm uninstall webpack -g
npm uninstall -g webpack-dev-server
npm install webpack@3.8.0 --save-dev 
npm install webpack-dev-server@2.9.7 --save-dev

참고




참고


Vanilla JS에서 SPA 라우팅 시스템 구현하기

profile
protect me from what i want

0개의 댓글