ES6 + Babel + Webpack + RxJS 설정

14919 단어 ES6rxjswebpackbabelES6

npm 에코시스템을 이용해서 초기 틀을 마련하고, 추가할 패키지를 명시하고 웹팩 설정을 하고 코드를 작성하고 테스트를 해보자.

npm

npm init -y
npm install 

package.json

{
  "name": "rxjs",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "webpack -w"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "rxjs": "^6.6.0"
  },
  "devDependencies": {
    "@babel/cli": "^7.7.0",
    "@babel/core": "^7.7.2",
    "@babel/plugin-proposal-class-properties": "^7.7.0",
    "@babel/preset-env": "^7.7.1",
    "babel-loader": "^8.1.0",
    "webpack": "^4.41.2",
    "webpack-cli": "^3.3.10"
  }
}

webpack.config.js

const path = require('path');

module.exports = {
  // enntry file
  entry: './src/js/index.js',
  // 컴파일 + 번들링된 js 파일이 저장될 경로와 이름 지정
  output: {
    path: path.resolve(__dirname, 'dist/js'),
    filename: 'bundle.js'
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        include: [
          path.resolve(__dirname, 'src/js')
        ],
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: ['@babel/preset-env'],
            plugins: ['@babel/plugin-proposal-class-properties']
          }
        }
      }
    ]
  },
  devtool: 'source-map',
  // https://webpack.js.org/concepts/mode/#mode-development
  mode: 'development'
};

code

import { Observable } from 'rxjs'

const hello = Observable.create(ob => {
    ob.next(1)
    ob.next(2)
    ob.next(3)
    ob.next(4)
    ob.next({
        name: "chulgu",
        phone: "010-1234"
    })
    ob.complete()
});
const sub = hello.subscribe(v => {
    console.log(v)
    if (typeof v === 'object') {
        console.log(v)
        console.log("==> ", v.name);
        console.log("==> ", v.phone);
        console.log("==> ", v.addr);
        if (v.addr === undefined) {
            // throw 'Parameter is not a addr!';
            const divide = 1 / 0;
            console.log(divide)
            if (divide === Infinity) {
                throw 'Zero error';
            }
        }
    }
}, e => console.log("error", e));

index.html

<!DOCTYPE html>
<html>
<body>
  <script src="./dist/js/bundle.js"></script>
</body>
</html>

좋은 웹페이지 즐겨찾기