14
13

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Greasemonkey で直接 CoffeeScript を書く方法

Last updated at Posted at 2012-12-26

(追記1)Firefox 21 以降 E4X がサポートされなくなったため、現行の Firefox では本記事のコードは動きません
(追記2)E4X を使わずに記述する方法に変更しました。

greasecoffee1.user.js
//;###
// ==UserScript==
// @name        coffeetest
// @namespace   http://example.com/coffeetest
// @include     *
// @grant       none
// @require     http://coffeescript.org/extras/coffee-script.js
// @version     1
// ==/UserScript==
CoffeeScript.eval((function(){/*
# coffeescript from here ###

class User
  constructor: ->
    @name = 'Coffee'

  call_name: ->
    alert "Mr. " + @name

(new User()).call_name()

# end of coffeescript #*/}).toString().split("\n").slice(1, -1).join("\n"));

使い方

class User の行から (new User()).call_name() の部分までが CoffeeScript として解釈されるので、この箇所に任意の処理を記述してください。また、==UserScript==で囲まれている部分は coffeescript の読み込み行を除いて、greasemonkey で定める通り自由に書くことができます。それ以外の箇所は、例えばただのコメントのように見える最後の行も変換に必要なので、消したり変更しないでください。

動作環境

上記のコードは単体で greasemonkey(javascript) としても coffeescript としても動作します。

Greasemonkey で書くのは基本的に小物スクリプトなので、わざわざ CoffeeScript を使う必要があるのかどうかはわかりませんが、どーーーしても CoffeeScript で書きたい僕のような人は使ってみてください。

補足1

毎回コンパイルするのが気になる人は、コンパイル結果を GM_setValue, GM_getValue すると良いです。

greasecoffee2.user.js
__js_code__ = (function(){/*
# coffeescript from here ###

alert 'hoge'

### end of coffeescript #*/}).toString().split("\n").slice(1, -1).join("\n");
if (GM_getValue('__last_js_code__') !== __js_code__) {
  GM_setValue('__last_js_code__', __js_code__);
  GM_setValue('__last_compiled__', CoffeeScript.compile(__js_code__));
}
eval(GM_getValue('__last_compiled__'));

補足2

先頭の行で //;### としているのは、javascript では1行コメントとして扱われる一方、coffeescript では正規表現オブジェクトのあとにブロックコメントが続くようにするため。(両方の言語で構文エラーにならないようにするためのハック)

参考リンク

http://jashkenas.github.com/coffee-script/
http://wiki.greasespot.net/Metadata_Block

14
13
2

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
14
13

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?