Webシステムを作るときに切り離せないのがJavaScriptです。Webブラウザ上で動くプログラミング言語として現状はJavaScriptしか動作しないので、必ず習得する必要があります。しかし、サーバサイドとクライアントで別な言語を使うのは不便です。 そこで使ってみたいのがTranscryptです。Python 3.6相当の記述が可能なJavaScript言語代替です。

Transcryptの使い方

TranscryptでjQueryを使った場合のコード例です。

__pragma__ ('alias', 'S', '$')
  
  def start ():
      def changeColors ():
          for div in S__divs:
              S (div) .css ({
                  'color': 'rgb({},{},{})'.format (* [int (256 * Math.random ()) for i in range (3)]),
              })
  
      S__divs = S ('div')
      changeColors ()
      window.setInterval (changeColors, 500)

Reactを使うこともできます。ただ、JSX部分が分かりづらいですね…。

# Helper functions


def h(elm_type, props='', *args):
    return React.createElement(elm_type, props, *args)


def render(react_element, destination_id, callback=lambda: None):
    container = document.getElementById(destination_id)
    ReactDOM.render(react_element, container, callback)


# Create a component


Hello = React.createClass({
    'displayName': 'Hello',

    'getInitialState': lambda: {'counter': 0},

    'updateCounter': lambda: (this.setState({'counter': this.state['counter']+1})),

    'componentDidMount': lambda: (setInterval(this.updateCounter, 1000)),

    'render': lambda: h('div', {'className': 'maindiv'},
                          h('h1', None, 'Hello ', this.props['name']),
                          h('p', None, 'Lorem ipsum dolor sit ame.'),
                          h('p', None, 'Counter: ', this.state['counter'])
                        )
})


# Render the component in a 'container' div

element = React.createElement(Hello, {'name': 'React!'})
render(element, 'container')

Transcryptを使うことでサーバサイドとクライアントサイドの言語が統一できます。外部ライブラリも使うことができるので、拡張性も担保されています。変換後のコードもそれほど見づらくならないのでデバッグも難しくないでしょう。

TranscryptはJavaScript製のオープンソース・ソフトウェア(Apache Licnese 2.0)です。

Transcrypt - Python in the browser - Lean, fast, open! QQuick/Transcrypt: Python 3.6 to JavaScript compiler - Lean, fast, open! -