LoginSignup
8
4

More than 5 years have passed since last update.

pipeline operatorを実際に使ってみる

Last updated at Posted at 2019-01-31

動機: TC39で策定中の新しい記法に触れたい

ES2019に含まれるであろう新しい記法などを知るのは楽しいですが
眺めているだけでなく実際に使って気持ちよくなりたくないですか。
ありがたいことにBabelを利用することでまだ採用されていない検討中の文法を先取りして試すことができます。

本記事では試しにpipeline operatorという記法を手元で実行してみます。
これは2018年1月現在、stage1: 提案の段階なので絶対にES2019には含まれない
参考: The TC39 Process https://tc39.github.io/process-document/

pipeline operator とは

まだ策定中の新しいJSの文法。
詳しくはこっち https://github.com/tc39/proposal-pipeline-operator
一瞬理解に苦しむけどRamdaとかで pipe を使ったことがあったり
bashでのパイプラインと連想するとスッっと頭に入ってくる。

準備

babelの周りをインストール

yarn init -y && \
yarn add -D @babel/core @babel/cli @babel/plugin-proposal-pipeline-operator

.babelrc を用意。

プラグインを追加することでpipeline operatorを使ったコードのトランスパイルができるようにしてあげます。

.babelrc


{
  "plugins": [
    [
      "@babel/plugin-proposal-pipeline-operator",
      {
        "proposal": "minimal"
      }
    ]
  ]
}

コードを書く

最初詰まったのですがarrow functionはカッコで括らないとbabelがビルドできないと怒ります

src/index.js
'claire redfield' 
  |> (name => name[0].toUpperCase() + name.substring(1))
  |> (name => `my name is ${name}`)
  |> console.log

ビルド & 実行


./node_modules/.bin/babel src -d . && node index.js

結果

Successfully compiled 1 file with Babel.
my name is Claire Redfield

クレア・レッドフィールドになれました。バイオRE2やってますか?

参考

8
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
4