イントロダクションIntroduction
Laravel Elixir(エリクサー:万能薬)は、Laravelアプリケーションのための基本的なGulpタスクを定義しており、きれいでスラスラかけるAPIを提供しています。Elixirは人気のあるCSSとJavascriptプリプロセッサー、それにテストツールもサポートしています。メソッドのチェーンを使用し、Elixirでアセットパイプラインを流暢に定義できます。例を見てください。Laravel Elixir provides a clean, fluent API for defining basic Gulp[http://gulpjs.com] tasks for your Laravel application. Elixir supports several common CSS and JavaScript pre-processors, and even testing tools. Using method chaining, Elixir allows you to fluently define your asset pipeline. For example:
elixir(function(mix) {
mix.sass('app.scss')
.coffee('app.coffee');
});
Gulpやアセットのコンパイルを始めようとして、頭がこんがらがっているようならLaravel Elixirを気に入ってもらえるでしょう。しかしながらアプリケーションの開発時に必要だというわけではありません。どんなアセットパイプラインツールを使用してもかまいませんし、使わなくても結構です。If you've ever been confused about how to get started with Gulp and asset compilation, you will love Laravel Elixir. However, you are not required to use it while developing your application. You are free to use any asset pipeline tool you wish, or even none at all.
インストールと準備Installation & Setup
NodeのインストールInstalling Node
Elixirを始める前、最初にNode.jsを開発機にインストール済みであることを確認してください。Before triggering Elixir, you must first ensure that Node.js is installed on your machine.
node -v
Laravel Homesteadならデフォルトのままでも必要なものが全部そろっています。しかしVagrantを使っていなくてもNodeのダウンロードページを読めば、簡単にインストールできます。By default, Laravel Homestead includes everything you need; however, if you aren't using Vagrant, then you can easily install Node by visiting their download page[http://nodejs.org/download/].
GulpGulp
次にGulpをグローバルNPMパッケージとしてインストールします。Next, you'll want to pull in Gulp[http://gulpjs.com] as a global NPM package:
npm install --global gulp
Laravel ElixirLaravel Elixir
残っているステップはElixirのインストールだけです。新しくLaravelをインストールすると、ルートディレクトリーにpackage.json
があることに気づくでしょう。PHPの代わりにNodeの依存パッケージが定義されている所が異なりますが、composer.json
ファイルと同じようなものだと考えてください。以下のコマンドで、依存パッケージをインストールしてください。The only remaining step is to
install Elixir! Within a fresh installation of
Laravel, you'll find a package.json
file in the root. Think of this like your
composer.json
file, except it defines
Node dependencies instead of PHP. You may install
the dependencies it references by
running:
npm install
Windowsシステムで開発を行っている場合、もしくはWindowsをホストとして仮想マシンを実行しているときは、--no-bin-links
を有効にしてnpm
install
コマンドを実行してください。If you are developing on a
Windows system or you are running your VM on a
Windows host system, you may need to run the
npm install
command with the
--no-bin-links
switch
enabled:
npm install --no-bin-links
Elixirの実行Running Elixir
ElixirはGulp上に構築されていますので、端末でgulp
コマンドを実行するだけでElixirタスクを走らせることができます。コマンドに--production
フラッグを付けることで、ElixirにCSSとJavaScriptファイルを圧縮するように指示できます。Elixir is built on top of
Gulp[http://gulpjs.com], so to run your
Elixir tasks you only need to run the
gulp
command in your terminal. Adding
the --production
flag to the command
will instruct Elixir to minify your CSS and
JavaScript files:
// 全タスク実行…
gulp
// 全タスクを実行し、全CSSとJavaScriptを圧縮する…
gulp --production
アセットの変更監視Watching Assets For Changes
アセットを変更するごとに端末でgulp
コマンドを実行するのは不便ですので、gulp
watch
コマンドを使用できます。このコマンドは端末で動き続けてアセットの変更を監視します。変化が起きると変更があるファイルは自動的にコンパイルされます。Since it is inconvenient to run
the gulp
command on your terminal after
every change to your assets, you may use the
gulp watch
command. This command will
continue running in your terminal and watch your
assets for any changes. When changes occur, new
files will automatically be compiled:
gulp watch
スタイルシート操作Working With Stylesheets
プロジェクトルートにあるgulpfile.js
ファイルに全Elixirタスクを構成します。Elixirタスクはアセットをどのようにコンパイルするか実際に定義するためにチェーンでつなげます。The gulpfile.js
file
in your project's root directory contains all of
your Elixir tasks. Elixir tasks can be chained
together to define exactly how your assets should be
compiled.
LessLess
LessをCSSへコンパイルするにはless
メソッドを使用します。less
メソッドはLessファイルがresources/assets/less
に保存されていることを想定しています。コンパイルされたCSSはデフォルトでpublic/css/app.css
へ保存されます。To compile
Less[http://lesscss.org/] into CSS, you may
use the less
method. The
less
method assumes that your Less
files are stored in
resources/assets/less
. By default, the
task will place the compiled CSS for this example in
public/css/app.css
:
elixir(function(mix) {
mix.less('app.less');
});
さらに複数のLessファイルを一つのCSSファイルへ結合できます。この結果のCSSもpublic/css/app.css
に保存されます。You may also combine multiple
Less files into a single CSS file. Again, the
resulting CSS will be placed in
public/css/app.css
:
elixir(function(mix) {
mix.less([
'app.less',
'controllers.less'
]);
});
コンパイル済みのCSSの出力先をカスタマイズしたい場合は、less
メソッドに第2引数で指定します。If you wish to customize the
output location of the compiled CSS, you may pass a
second argument to the less
method:
elixir(function(mix) {
mix.less('app.less', 'public/stylesheets');
});
// 出力ファイル名を指定する…
elixir(function(mix) {
mix.less('app.less', 'public/stylesheets/style.css');
});
SassSass
sass
メソッドはSassをCSSへコンパイルします。Sassファイルはresources/assets/sass
へ保存されていると想定します。このメソッドは次のように使用します。The sass
method
allows you to compile
Sass[http://sass-lang.com/] into CSS.
Assuming your Sass files are stored at
resources/assets/sass
, you may use the
method like so:
elixir(function(mix) {
mix.sass('app.scss');
});
less
メソッドと同様に複数のSassファイルを一つのCSSファイルへまとめることができ、結果のCSSを出力するディレクトリーもカスタマイズできます。Again, like the less
method, you may compile multiple Sass files into a
single CSS file, and even customize the output
directory of the resulting CSS:
elixir(function(mix) {
mix.sass([
'app.scss',
'controllers.scss'
], 'public/assets/css');
});
通常のCSSPlain CSS
通常のCSSスタイルシートを一つのファイルに結合したい場合は、styles
メソッドを使います。このメソッドに渡すパスはresources/assets/css
からの相対位置で、結果のCSSはpublic/css/all.css
に保存されます。If you would just like to combine
some plain CSS stylesheets into a single file, you
may use the styles
method. Paths passed
to this method are relative to the
resources/assets/css
directory and the
resulting CSS will be placed in
public/css/all.css
:
elixir(function(mix) {
mix.styles([
'normalize.css',
'main.css'
]);
});
もちろんstyles
メソッドの第2引数を指定すれば、結果の出力ファイルをカスタマイズできます。Of course, you may also output
the resulting file to a custom location by passing a
second argument to the styles
method:
elixir(function(mix) {
mix.styles([
'normalize.css',
'main.css'
], 'public/assets/css');
});
ソースマップSource Maps
ソースマップ生成はデフォルトで有効になっています。各ファイルをコンパイルするごとに、*.css.map
ファイルが同じディレクトリーに生成されます。このマッピングはデバッグの時にブラウザ上でコンパイル済みのスタイルシートセレクターからオリジナルのSassやLess定義を見つけるのに役立ちますSource maps are enabled out of
the box. So, for each file that is compiled you will
find a companion *.css.map
file in the
same directory. This mapping allows you to trace
your compiled stylesheet selectors back to your
original Sass or Less while debugging in your
browser.
CSSのためにソースマップを生成したくなければ、設定オプションで無効にしてください。If you do not want source maps generated for your CSS, you may disable them using a simple configuration option:
elixir.config.sourcemaps = false;
elixir(function(mix) {
mix.sass('app.scss');
});
スクリプト操作Working With Scripts
ElixirはECMAScript 6のコンパイル、CoffeeScriptのコンパイル、Browserify、圧縮、JavaScriptファイルの結合などのJavaScript操作を手助けする多くの機能も提供しています。Elixir also provides several functions to help you work with your JavaScript files, such as compiling ECMAScript 6, compiling CoffeeScript, Browserify, minification, and simply concatenating plain JavaScript files.
CoffeeScriptCoffeeScript
coffee
メソッドはCoffeeScriptをJavaScriptへコンパイルするために使用します。coffee
関数はresources/assets/coffee
ディレクトリーからの相対パスの文字列か配列を引数に受け取り、public/js
ディレクトリーにapp.js
ファイルを生成します。The coffee
method
may be used to compile
CoffeeScript[http://coffeescript.org/] into
plain JavaScript. The coffee
function
accepts a string or array of CoffeeScript files
relative to the resources/assets/coffee
directory and generates a single app.js
file in the public/js
directory:
elixir(function(mix) {
mix.coffee(['app.coffee', 'controllers.coffee']);
});
BrowserifyBrowserify
Elixirはbrowserify
メソッドも用意しており、ブラウザーとECMAScript
6を使用するためにモジュールをrequireする全ての利点を享受できます。Elixir also ships with a
browserify
method, which gives you all
the benefits of requiring modules in the browser and
using ECMAScript 6.
このタスクはスクリプトがresources/assets/js
へ設置されていると考え、結果をpublic/js/main.js
ファイルへ書き出します。This task assumes that your
scripts are stored in
resources/assets/js
and will place the
resulting file in
public/js/main.js
:
elixir(function(mix) {
mix.browserify('main.js');
});
Browserifyは最初からPartialifyとBabelifyトランスフォーマーを含んでいますが、お望みならvueifyをインストールし追加することもできます。While Browserify ships with the Partialify and Babelify transformers, you're free to install and add more if you wish:
npm install aliasify --save-dev
elixir.config.js.browserify.transformers.push({
name: 'aliasify',
options: {}
});
elixir(function(mix) {
mix.browserify('main.js');
});
BabelBabel
babel
メソッドはECMAScript
6と7をJavaScriptへコンパイルするために使用します。この関数はresources/assets/js
ディレクトリーからの相対ファイルパスの配列を引数に受け取り、public/js
ディレクトリーのall.js
ファイルを生成します。The babel
method may
be used to compile ECMAScript 6 and
7[https://babeljs.io/docs/learn-es2015/]
into plain JavaScript. This function accepts an
array of files relative to the
resources/assets/js
directory, and
generates a single all.js
file in the
public/js
directory:
elixir(function(mix) {
mix.babel([
'order.js',
'product.js'
]);
});
別の場所へ出力したい場合は、希望するパスを第2引数に指定してください。このメソッドの使い方と機能はmix.scripts()
と同じで、Babelのコンパイルを行う点のみ異なります。To choose a different output
location, simply specify your desired path as the
second argument. The signature and functionality of
this method are identical to
mix.scripts()
, excluding the Babel
compilation.
JavaScriptScripts
複数のJavaScriptファイルを一つのファイルへまとめたい場合は、scripts
メソッドを使用します。If you have multiple JavaScript
files that you would like to combine into a single
file, you may use the scripts
method.
scripts
メソッドは全パスをresources/assets/js
からの相対位置であると想定し、結果をデフォルトでpublic/js/all.js
に置きます。The scripts
method
assumes all paths are relative to the
resources/assets/js
directory, and will
place the resulting JavaScript in
public/js/all.js
by default:
elixir(function(mix) {
mix.scripts([
'jquery.js',
'app.js'
]);
});
複数のスクリプトを別々のファイルにまとめたい場合は、scripts
メソッドを複数回呼び出してください。メソッドの第2引数でそれぞれの結合ファイル名を指定します。If you need to combine multiple
sets of scripts into different files, you may make
multiple calls to the scripts
method.
The second argument given to the method determines
the resulting file name for each
concatenation:
elixir(function(mix) {
mix.scripts(['app.js', 'controllers.js'], 'public/js/app.js')
.scripts(['forum.js', 'threads.js'], 'public/js/forum.js');
});
指定したディレクトリーの全スクリプトを結合するには、scriptsIn
メソッドを使います。結果のJavaScriptはpublic/js/all.js
に設置されます。If you need to combine all of the
scripts in a given directory, you may use the
scriptsIn
method. The resulting
JavaScript will be placed in
public/js/all.js
:
elixir(function(mix) {
mix.scriptsIn('public/js/some/directory');
});
ファイルとディレクトリーのコピーCopying Files & Directories
copy
メソッドはファイルとディレクトリーを新しい場所へコピーするために使用できます。全操作はプロジェクトルートディレクトリーからの相対位置で指定します。The copy
method may
be used to copy files and directories to new
locations. All operations are relative to the
project's root directory:
elixir(function(mix) {
mix.copy('vendor/foo/bar.css', 'public/css/bar.css');
});
elixir(function(mix) {
mix.copy('vendor/package/views', 'resources/views');
});
バージョン付け/キャッシュ破壊Versioning / Cache Busting
多くの開発者がコンパイルしたアセットにタイムスタンプや一意なトークンをサフィックスとして付加し、保存されている古いコードの代わりに真新しいアセットを強制的にロードさせています。Elixirはこれをversion
メソッドで処理します。Many developers suffix their
compiled assets with a timestamp or unique token to
force browsers to load the fresh assets instead of
serving stale copies of the code. Elixir can handle
this for you using the version
method.
version
メソッドはpublic
ディレクトリーからの相対パスファイル名を受け取り、ファイル名に一意なハッシュを付けることでキャッシュを破壊します。たとえば生成されたファイル名はall-16d570a7.css
のような名前になります。The version
method
accepts a file name relative to the
public
directory, and will append a
unique hash to the filename, allowing for
cache-busting. For example, the generated file name
will look something like:
all-16d570a7.css
:
elixir(function(mix) {
mix.version('css/all.css');
});
バージョンが付いたファイルを生成した後、ビューの中からLaravelのグローバルelixir
PHPヘルパ関数を使い、ハッシュが付いたアセットをロードすることができます。elixir
関数はハッシュをつけたファイル名を自動的に決定します。After generating the versioned
file, you may use Laravel's global
elixir
PHP helper function within your
views[/docs/{{version}}/views] to load the
appropriately hashed asset. The elixir
function will automatically determine the name of
the hashed file:
<link rel="stylesheet" href="{{ elixir('css/all.css') }}">
複数ファイルのバージョン付けVersioning Multiple Files
version
メソッドへ配列で複数ファイルを渡すこともできます。You may pass an array to the
version
method to version multiple
files:
elixir(function(mix) {
mix.version(['css/all.css', 'js/app.js']);
});
ファイルにバージョンが付けられたら、elixir
ヘルパ関数でハッシュが付いた実際のファイルへリンクを生成することができます。elixir
ヘルパ関数にはハッシュをつけていないファイル名を渡す必要があることを覚えておきましょう。Once the files have been
versioned, you may use the elixir
helper function to generate links to the proper
hashed files. Remember, you only need to pass the
name of the un-hashed file to the
elixir
helper function. The helper will
use the un-hashed name to determine the current
hashed version of the file:
<link rel="stylesheet" href="{{ elixir('css/all.css') }}">
<script src="{{ elixir('js/app.js') }}"></script>
BrowserSyncBrowserSync
BrowserSyncはフロントエンドのリソースに変更が起きたときに、Webブラウザを自動的に再読込します。gulp
watch
コマンド実行時にBrowserSyncサーバーを起動するようにElixirへ指示するため、browserSync
メソッドが利用できます。BrowserSync automatically
refreshes your web browser after you make changes to
your front-end resources. You can use the
browserSync
method to instruct Elixir
to start a BrowserSync server when you run the
gulp watch
command:
elixir(function(mix) {
mix.browserSync();
});
gulp
watch
を実行したら、ブラウザ同期を利用するにはhttp://homestead.app:3000
でWebアプリケーションにアクセスしてください。ローカル開発にhomestead.app
以外のドメインを使用しているなら、browserSync
メソッドの最初の引数としてオプションの配列を渡してください。Once you run gulp
watch
, access your web application using
port 3000 to enable browser syncing:
http://homestead.app:3000
. If you're
using a domain other than homestead.app
for local development, you may pass an array of
options[http://www.browsersync.io/docs/options/]
as the first argument to the
browserSync
method:
elixir(function(mix) {
mix.browserSync({
proxy: 'project.app'
});
});
既存Gulpタスクの呼び出しCalling Existing Gulp Tasks
既存のGulpタスクをElixirから呼び出すにはtask
メソッドを使用します。たとえば呼びだされた時にただちょっとしたテキストを話すGulpタスクを考えてみてください。If you need to call an existing
Gulp task from Elixir, you may use the
task
method. As an example, imagine
that you have a Gulp task that simply speaks a bit
of text when called:
gulp.task('speak', function() {
var message = 'Tea...Earl Grey...Hot';
gulp.src('').pipe(shell('say ' message));
});
このタスクをElixirから呼び出すにはmix.task
メソッドを使い、メソッドの唯一の引数にタスク名を指定してください。If you wish to call this task
from Elixir, use the mix.task
method
and pass the name of the task as the only argument
to the method:
elixir(function(mix) {
mix.task('speak');
});
カスタムタスク監視Custom Watchers
カスタムタスクを実行するための監視対象ファイルを登録するには、task
メソッドの第2引数に正規表現で指定してください。If you need to register a watcher
to run your custom task each time some files are
modified, pass a regular expression as the second
argument to the task
method:
elixir(function(mix) {
mix.task('speak', 'app/**/*.php');
});
Elixir拡張の定義Writing Elixir Extensions
Elixirのtask
メソッドが提供しているより、さらに柔軟性が求められる場合は、カスタムElixir拡張を作成してください。Elixir拡張でカスタムタスクへ引数を引き渡せます。たとえば以下のような拡張を書いたとしましょう。If you need more flexibility than
Elixir's task
method can provide, you
may create custom Elixir extensions. Elixir
extensions allow you to pass arguments to your
custom tasks. For example, you could write an
extension like so:
// File: elixir-extensions.js
var gulp = require('gulp');
var shell = require('gulp-shell');
var Elixir = require('laravel-elixir');
var Task = Elixir.Task;
Elixir.extend('speak', function(message) {
new Task('speak', function() {
return gulp.src('').pipe(shell('say ' message));
});
});
// mix.speak('Hello World');
これだけです!
Gulp限定のロジックはTask
コンストラクターの第2引数として渡している関数に設置しなくてはならない点に注目です。これをGulpfileの先頭に設置するか、代わりにカスタムタスクファイルとして外部ファイルにします。たとえば拡張をelixir-extensions.js
ファイルに設置し、次のようにメインのGulpfile
から読み込みます。That's it! Notice that your
Gulp-specific logic should be placed within the
function passed as the second argument to the
Task
constructor. You may either place
this at the top of your Gulpfile, or instead extract
it to a custom tasks file. For example, if you place
your extensions in
elixir-extensions.js
, you may require
the file from your main Gulpfile
like
so:
// ファイル: Gulpfile.js
var elixir = require('laravel-elixir');
require('./elixir-extensions')
elixir(function(mix) {
mix.speak('Tea, Earl Grey, Hot');
});
カスタム監視Custom Watchers
gulp
watch
が実行されている間にカスタムタスクを再起動したい場合は、監視タスクを登録します。If you would like your custom
task to be re-triggered while running gulp
watch
, you may register a
watcher:
new Task('speak', function() {
return gulp.src('').pipe(shell('say ' message));
})
.watch('./app/**');