Readouble

Laravel 5.7 アセットのコンパイル(Mix)

イントロダクションIntroduction

Laravel Mixは多くの一般的なCSSとJavaScriptのプリプロセッサを使用し、Laravelアプリケーションために、構築過程をWebpackでスラスラと定義できるAPIを提供しています。シンプルなメソッドチェーンを使用しているため、アセットパイプラインを流暢に定義できます。例を見てください。Laravel Mix[https://github.com/JeffreyWay/laravel-mix] provides a fluent API for defining Webpack build steps for your Laravel application using several common CSS and JavaScript pre-processors. Through simple method chaining, you can fluently define your asset pipeline. For example:

mix.js('resources/js/app.js', 'public/js')
   .sass('resources/sass/app.scss', 'public/css');

Webpackやアセットのコンパイルを始めようとして、混乱と圧倒を感じているならLaravel Mixを気に入ってもらえるでしょう。しかし、アプリケーションの開発時に必要だというわけではありません。どんなアセットパイプラインツールを使用してもかまいませんし、使わなくても良いのです。If you've ever been confused and overwhelmed about getting started with Webpack and asset compilation, you will love Laravel Mix. 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

Mixを始める前、最初にNode.jsとNPMを開発機へ確実にインストールしてください。Before triggering Mix, you must first ensure that Node.js and NPM are installed on your machine.

node -v
npm -v

Laravel Homesteadならデフォルトのままでも必要なものが全部そろっています。しかし、Vagrantを使っていなくても、ダウンロードページを読めば、NodeとNPMは簡単にインストールできます。By default, Laravel Homestead includes everything you need; however, if you aren't using Vagrant, then you can easily install the latest version of Node and NPM using simple graphical installers from their download page[https://nodejs.org/en/download/].

Laravel MixLaravel Mix

残っているステップはLaravel Mixのインストールだけです。新しくLaravelをインストールすると、ルートディレクトリにpackage.jsonがあることに気づくでしょう。PHPの代わりにNodeの依存パッケージが定義されている所が異なりますが、composer.jsonファイルと同じようなものだと考えてください。以下のコマンドで、依存パッケージをインストールしてください。The only remaining step is to install Laravel Mix. Within a fresh installation of Laravel, you'll find a package.json file in the root of your directory structure. The default package.json file includes everything you need to get started. 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

Mixの実行Running Mix

MixはWebpack上の設定レイヤーですから、Laravelに含まれるpackage.jsonファイル上のNPMスクリプトの一つをMixの実行で起動してください。Mix is a configuration layer on top of Webpack[https://webpack.js.org], so to run your Mix tasks you only need to execute one of the NPM scripts that is included with the default Laravel package.json file:

// 全タスク実行
npm run dev

// 全タスク実行を実行し、出力を圧縮
npm run production

アセット変更の監視Watching Assets For Changes

npm run watchコマンドはターミナルで実行し続け、関連ファイル全部の変更を監視します。Webpackは変更を感知すると、アセットを自動的に再コンパイルします。The npm run watch command will continue running in your terminal and watch all relevant files for changes. Webpack will then automatically recompile your assets when it detects a change:

npm run watch

特定の環境のWebpackでは、ファイル変更時に更新されないことがあります。自分のシステムでこれが起きた場合は、watch-pollコマンドを使用してください。You may find that in certain environments Webpack isn't updating when your files change. If this is the case on your system, consider using the watch-poll command:

npm run watch-poll

スタイルシートの操作Working With Stylesheets

webpack.mix.jsファイルは全アセットコンパイルのエントリポイントです。Webpackの軽い設定ラッパーだと考えてください。Mixタスクはアセットをどのようにコンパイルすべきかを正確に定義するため、チェーンでつなげます。The webpack.mix.js file is your entry point for all asset compilation. Think of it as a light configuration wrapper around Webpack. Mix tasks can be chained together to define exactly how your assets should be compiled.

LessLess

LessをCSSへコンパイルするにはlessメソッドを使用します。最も主要なapp.lessファイルをpublic/css/app.cssとしてコンパイルしてみましょう。The less method may be used to compile Less[http://lesscss.org/] into CSS. Let's compile our primary app.less file to public/css/app.css.

mix.less('resources/less/app.less', 'public/css');

複数のファイルをコンパイルするには、lessメソッドを複数回呼び出します。Multiple calls to the less method may be used to compile multiple files:

mix.less('resources/less/app.less', 'public/css')
   .less('resources/less/admin.less', 'public/css');

コンパイル済みのCSSのファイル名をカスタマイズしたい場合は、lessの第2引数にファイルのフルパスを指定してください。If you wish to customize the file name of the compiled CSS, you may pass a full file path as the second argument to the less method:

mix.less('resources/less/app.less', 'public/stylesheets/styles.css');

裏で動作しているLessプラグインのオプションをオーバーライドする必要が起きたら、mix.less()の第3引数にオブジェクトを渡してください。If you need to override the underlying Less plug-in options[https://github.com/webpack-contrib/less-loader#options], you may pass an object as the third argument to mix.less():

mix.less('resources/less/app.less', 'public/css', {
    strictMath: true
});

SassSass

sassメソッドは、SassをCSSへコンパイルします。次のように使用します。The sass method allows you to compile Sass[https://sass-lang.com/] into CSS. You may use the method like so:

mix.sass('resources/sass/app.scss', 'public/css');

lessメソッドと同様に、複数のSassファイルを別々のCSSファイルへコンパイルできますし、結果のCSSの出力ディレクトリをカスタマイズ可能です。Again, like the less method, you may compile multiple Sass files into their own respective CSS files and even customize the output directory of the resulting CSS:

mix.sass('resources/sass/app.sass', 'public/css')
   .sass('resources/sass/admin.sass', 'public/css/admin');

さらに、Node-Sassプラグインオプションを第3引数に指定できます。Additional Node-Sass plug-in options[https://github.com/sass/node-sass#options] may be provided as the third argument:

mix.sass('resources/sass/app.sass', 'public/css', {
    precision: 5
});

StylusStylus

LessやSassと同様に、stylusメソッドにより、StylusをCSSへコンパイルできます。Similar to Less and Sass, the stylus method allows you to compile Stylus[http://stylus-lang.com/] into CSS:

mix.stylus('resources/stylus/app.styl', 'public/css');

さらに、Ruptureのような、追加のStylusプラグインをインストールすることもできます。最初に、NPM (npm install rupture)による質問でプラグインをインストールし、それからmix.stylus()の中で呼び出してください。You may also install additional Stylus plug-ins, such as Rupture[https://github.com/jescalan/rupture]. First, install the plug-in in question through NPM (npm install rupture) and then require it in your call to mix.stylus():

mix.stylus('resources/stylus/app.styl', 'public/css', {
    use: [
        require('rupture')()
    ]
});

PostCSSPostCSS

強力なCSS加工ツールであるPostCSSも、Laravel Mixには最初から含まれています。デフォルトでは、自動的に必要なCSS3ベンダープレフィックスを適用する、人気のAutoprefixerプラグインを利用します。しかし、アプリケーションに適したプラグインを自由に追加できます。最初に、NPMにより希望のプラグインをインストールし、それからwebpack.mix.jsの中から参照してください。PostCSS[https://postcss.org/], a powerful tool for transforming your CSS, is included with Laravel Mix out of the box. By default, Mix leverages the popular Autoprefixer[https://github.com/postcss/autoprefixer] plug-in to automatically apply all necessary CSS3 vendor prefixes. However, you're free to add any additional plug-ins that are appropriate for your application. First, install the desired plug-in through NPM and then reference it in your webpack.mix.js file:

mix.sass('resources/sass/app.scss', 'public/css')
   .options({
        postCss: [
            require('postcss-css-variables')()
        ]
   });

平文CSSPlain CSS

平文のCSSスタイルシートを一つのファイルへ結合したい場合は、stylesメソッドを使って下さい。If you would just like to concatenate some plain CSS stylesheets into a single file, you may use the styles method.

mix.styles([
    'public/css/vendor/normalize.css',
    'public/css/vendor/videojs.css'
], 'public/css/all.css');

URL処理URL Processing

Laravel MixはWebpack上に構築されているため、Webpackのコンセプトを理解することが重要です。CSSコンパイルのため、Webpackはスタイルシート中のurl()呼び出しをリライトし、最適化します。最初は奇妙に聴こえるかもしれませんが、これは非常に強力な機能の一部です。画像への相対URLを含んだSassをコンパイルするのを想像してください。Because Laravel Mix is built on top of Webpack, it's important to understand a few Webpack concepts. For CSS compilation, Webpack will rewrite and optimize any url() calls within your stylesheets. While this might initially sound strange, it's an incredibly powerful piece of functionality. Imagine that we want to compile Sass that includes a relative URL to an image:

.example {
    background: url('../images/example.png');
}

Note: note 絶対パスをurl()へ指定しても、URL書き換えの対象外になります。たとえば、url('/images/thing.png')や、url('http://example.com/images/thing.png')は変更されません。{note} Absolute paths for any given url() will be excluded from URL-rewriting. For example, url('/images/thing.png') or url('http://example.com/images/thing.png') won't be modified.

デフォルト動作として、Laravel MixとWebpackがexample.pngを見つけると、それをpublic/imagesフォルダへコピーします。それから、生成したスタイルシート中のurl()を書き換えます。By default, Laravel Mix and Webpack will find example.png, copy it to your public/images folder, and then rewrite the url() within your generated stylesheet. As such, your compiled CSS will be:

.example {
    background: url(/images/example.png?d41d8cd98f00b204e9800998ecf8427e);
}

この機能は便利ですが、好きなようにフォルダ構造を設定することもできます。その場合、以下のようにurl()リライトを停止してください。As useful as this feature may be, it's possible that your existing folder structure is already configured in a way you like. If this is the case, you may disable url() rewriting like so:

mix.sass('resources/app/app.scss', 'public/css')
   .options({
      processCssUrls: false
   });

これをwebpack.mix.jsファイルへ追加することで、Mixはどんなurl()に一致することも、publicディレクトリへアセットをコピーすることもしなくなります。言い換えれば、コンパイル済みのCSSは、みなさんがタイプした内容そのままに見えるでしょう。With this addition to your webpack.mix.js file, Mix will no longer match any url() or copy assets to your public directory. In other words, the compiled CSS will look just like how you originally typed it:

.example {
    background: url("../images/thing.png");
}

ソースマップSource Maps

デフォルトでは無効になっているため、webpack.mix.jsファイルでmix.sourceMaps()を呼び出すことで、ソースマップは有効になります。コンパイルコストと実行パフォーマンスコストはかかりますが、これによりコンパイル済みアセットを使用する時に、ブラウザの開発ツール向けの追加デバッグ情報が提供されます。Though disabled by default, source maps may be activated by calling the mix.sourceMaps() method in your webpack.mix.js file. Though it comes with a compile/performance cost, this will provide extra debugging information to your browser's developer tools when using compiled assets.

mix.js('resources/js/app.js', 'public/js')
   .sourceMaps();

JavaScriptの操作Working With JavaScript

MixはECMAScript 2015のコンパイル、モジュール結合、圧縮やJavaScriptファイルの結合などの操作を手助けする、多くの機能を提供しています。それだけでなく、設定をカスタマイズする必要は全く無く、全てがシームレスに動作します。Mix provides several features to help you work with your JavaScript files, such as compiling ECMAScript 2015, module bundling, minification, and concatenating plain JavaScript files. Even better, this all works seamlessly, without requiring an ounce of custom configuration:

mix.js('resources/js/app.js', 'public/js');

このコード一行で、以下の利点を享受できます。With this single line of code, you may now take advantage of:

- ES2015記法 - モジュール - `.vue`ファイルのコンパイル - 開発環境向けに圧縮

ベンダの抽出Vendor Extraction

全てのアプリケーション固有のJavaScriptとベンダーライブラリを結合することにより、発生する可能性がある欠点は、長期間のキャッシュが効きづらくなることです。たとえば、アプリケーションコードの一箇所を更新すれば、変更のないベンダーライブラリーの全てを再度ダウンロードするように、ブラウザに共用することになります。One potential downside to bundling all application-specific JavaScript with your vendor libraries is that it makes long-term caching more difficult. For example, a single update to your application code will force the browser to re-download all of your vendor libraries even if they haven't changed.

アプリケーションのJavaScriptを頻繁に更新したい場合は、全ベンダーライブラリを専用のファイルへ分ける方法を考慮する必要があります。これにより、アプリケーションコードの変更は、大きなvendor.jsファイルのキャッシュへ影響しなくなります。Mixのextractメソッドで簡単に実現できます。If you intend to make frequent updates to your application's JavaScript, you should consider extracting all of your vendor libraries into their own file. This way, a change to your application code will not affect the caching of your large vendor.js file. Mix's extract method makes this a breeze:

mix.js('resources/js/app.js', 'public/js')
   .extract(['vue'])

extractメソッドは全ライブラリとモジュールの配列を受け取り、vendor.jsへ別にまとめます。上記のコードを例にすると、Mix配下のファイルを生成します。The extract method accepts an array of all libraries or modules that you wish to extract into a vendor.js file. Using the above snippet as an example, Mix will generate the following files:

- `public/js/manifest.js`: **Webpackマニフェストランタイム** - `public/js/vendor.js`: **ベンダーライブラリ** - `public/js/app.js`: **アプリケーションコード**

JavaScriptエラーを起こさないために、以下のファイルは順番通りにロードしてください。To avoid JavaScript errors, be sure to load these files in the proper order:

<script src="/js/manifest.js"></script>
<script src="/js/vendor.js"></script>
<script src="/js/app.js"></script>

ReactReact

MixはReactをサポートするために、Babelプラグインを自動的にインストールします。使用開始するためには、mix.js()の呼び出しをmix.react()に置換してください。Mix can automatically install the Babel plug-ins necessary for React support. To get started, replace your mix.js() call with mix.react():

mix.react('resources/js/app.jsx', 'public/js');

実際には、Mixは最適なBabelプラグインとしてbabel-preset-reactをダウンロードし、取り込んでいます。Behind the scenes, Mix will download and include the appropriate babel-preset-react Babel plug-in.

バニラJSVanilla JS

スタイルシートをmix.styles()により結合するのと同様に、多くのJavaScriptファイルをscripts()メソッドで結合し、圧縮できます。Similar to combining stylesheets with mix.styles(), you may also combine and minify any number of JavaScript files with the scripts() method:

mix.scripts([
    'public/js/admin.js',
    'public/js/dashboard.js'
], 'public/js/all.js');

この選択肢は特にWebpackによる操作を必要としないレガシープロジェクトに便利です。This option is particularly useful for legacy projects where you don't require Webpack compilation for your JavaScript.

lightbulb">Tip!! mix.scripts()のちょっとしたバリエーションとしてmix.babel()があります。このメソッドはscriptsと同じ使い方です。しかし、結合したファイルはBabelにより編集され、ES2015コードを全てのブラウザーが理解できるバニラJavaScriptへ変換します。{tip} A slight variation of mix.scripts() is mix.babel(). Its method signature is identical to scripts; however, the concatenated file will receive Babel compilation, which translates any ES2015 code to vanilla JavaScript that all browsers will understand.

Webpackカスタム設定Custom Webpack Configuration

Laravel Mixはできるだけ素早く実行できるように、裏で事前に設定済みのwebpack.config.jsファイルを参照しています。時々、このファイルを変更する必要が起きるでしょう。参照する必要がある特別なローダやプラグインがあったり、Sassの代わりにStylusを使うのが好みであるかもしれません。そうした場合、2つの選択肢があります。Behind the scenes, Laravel Mix references a pre-configured webpack.config.js file to get you up and running as quickly as possible. Occasionally, you may need to manually modify this file. You might have a special loader or plug-in that needs to be referenced, or maybe you prefer to use Stylus instead of Sass. In such instances, you have two choices:

カスタム設定のマージMerging Custom Configuration

Mixはオーバーライドする短いWebpack設定をマージできるように、便利なwebpackConfigメソッドを提供しています。これは、webpack.config.jsファイルをコピーし、独自バージョンをメンテナンスする必要がないため、やや魅力的な選択しです。webpackConfigメソッドは、適用したいWebpack限定設定を含むオブジェクトを引数に取ります。Mix provides a useful webpackConfig method that allows you to merge any short Webpack configuration overrides. This is a particularly appealing choice, as it doesn't require you to copy and maintain your own copy of the webpack.config.js file. The webpackConfig method accepts an object, which should contain any Webpack-specific configuration[https://webpack.js.org/configuration/] that you wish to apply.

mix.webpackConfig({
    resolve: {
        modules: [
            path.resolve(__dirname, 'vendor/laravel/spark/resources/assets/js')
        ]
    }
});

カスタム設定ファイルCustom Configuration Files

Webpack設定をすべてカスタマイズしたい場合は、node_modules/laravel-mix/setup/webpack.config.jsをプロジェクトのルートディレクトリへコピーしてください。次に、package.jsonファイル中の--config参照を全て新しくコピーした設定ファイルに変更します。カスタマイズにこのアプローチを取る場合は、Mixのwebpack.config.jsに対するアップストリームの機能変更を自分でカスタマイズするファイルへマージする必要があります。If you would like to completely customize your Webpack configuration, copy the node_modules/laravel-mix/setup/webpack.config.js file to your project's root directory. Next, point all of the --config references in your package.json file to the newly copied configuration file. If you choose to take this approach to customization, any future upstream updates to Mix's webpack.config.js must be manually merged into your customized file.

ファイル/ディレクトリコピーCopying Files & Directories

copyメソッドは、ファイルやディレクトリを新しい場所へコピーします。これはnode_modulesディレクトリ中の特定のアセットをpublicフォルダへ再配置する必要がある場合に便利です。The copy method may be used to copy files and directories to new locations. This can be useful when a particular asset within your node_modules directory needs to be relocated to your public folder.

mix.copy('node_modules/foo/bar.css', 'public/css/bar.css');

ディレクトリのコピー時は、copyメソッドはディレクトリ構造をフラットにします。元の構造を保持したい場合は、copyDirectoryメソッドを代わりに使用してください。When copying a directory, the copy method will flatten the directory's structure. To maintain the directory's original structure, you should use the copyDirectory method instead:

mix.copyDirectory('resources/img', 'public/img');

バージョン付け/キャッシュ対策Versioning / Cache Busting

多くの開発者は古いコードが提供され続けないように、新しいアセットがブラウザにロードされるよう、タイムスタンプやユニークなトークンをコンパイル済みのアセットへサフィックスとして付加しています。Mixでは、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. Mix can handle this for you using the version method.

versionメソッドは、キャッシュを簡単に破壊できるようにするため、コンパイル済みファイルのファイル名に一意のハッシュを自動的に付け加えます。The version method will automatically append a unique hash to the filenames of all compiled files, allowing for more convenient cache busting:

mix.js('resources/js/app.js', 'public/js')
   .version();

バージョン付されたファイルを生成した後は、適切にバージョン付けされたアセットのURLを生成するため、Laravelのグローバルmix関数をビューの中で使用してください。After generating the versioned file, you won't know the exact file name. So, you should use Laravel's global mix function within your views[/docs/{{version}}/views] to load the appropriately hashed asset. The mix function will automatically determine the current name of the hashed file:

<script src="{{ mix('/js/app.js') }}"></script>

バージョン付けしたファイルは、通常開発に必要ないため、npm run productionを実行するときのみ、バージョン付けするように指示したいと思うでしょう。Because versioned files are usually unnecessary in development, you may instruct the versioning process to only run during npm run production:

mix.js('resources/js/app.js', 'public/js');

if (mix.inProduction()) {
    mix.version();
}

BrowsersyncリロードBrowsersync Reloading

BrowserSyncは自動的にファイルの変更を監視し、手動で再読込しなくても変更をブラウザに反映してくれます。mix.browserSync()メソッドを呼び出し、有効にします。BrowserSync[https://browsersync.io/] can automatically monitor your files for changes, and inject your changes into the browser without requiring a manual refresh. You may enable support by calling the mix.browserSync() method:

mix.browserSync('my-domain.test');

// もしくは

// https://browsersync.io/docs/options
mix.browserSync({
    proxy: 'my-domain.test'
});

このメソッドには文字列(プロキシ)かオブジェクト(BrowserSync設定)のどちらかを渡します。次に、npm run watchコマンドにより、Webpackの開発サーバを起動します。これでスクリプトかPHPファイルを変更すると、すぐにページが再読込され、変更が反映されるのを目にするでしょう。You may pass either a string (proxy) or object (BrowserSync settings) to this method. Next, start Webpack's dev server using the npm run watch command. Now, when you modify a script or PHP file, watch as the browser instantly refreshes the page to reflect your changes.

環境変数Environment Variables

.envファイルの中でキーにMIX_をプリフィックスとしてつけることで、環境変数をMixへ注入できます。You may inject environment variables into Mix by prefixing a key in your .env file with MIX_:

MIX_SENTRY_DSN_PUBLIC=http://example.com

.envファイルで定義すると、process.envオブジェクトを通じてアクセスできるようになります。watchタスク実行中に、その値が変化した場合は、タスクを再起動する必要があります。After the variable has been defined in your .env file, you may access via the process.env object. If the value changes while you are running a watch task, you will need to restart the task:

process.env.MIX_SENTRY_DSN_PUBLIC

通知Notifications

可能な場合、Mixは自動的に各バンドルをOS通知で表示します。これにより、コンパイルが成功したのか、失敗したのか、即座にフィードバックが得られます。しかし、こうした通知を無効にしたい場合もあるでしょう。一例は、実働サーバでMixを起動する場合です。disableNotificationsメソッドにより、通知を無効にできます。When available, Mix will automatically display OS notifications for each bundle. This will give you instant feedback, as to whether the compilation was successful or not. However, there may be instances when you'd prefer to disable these notifications. One such example might be triggering Mix on your production server. Notifications may be deactivated, via the disableNotifications method.

mix.disableNotifications();

章選択

設定

明暗テーマ
light_mode
dark_mode
brightness_auto システム設定に合わせる
テーマ選択
photo_size_select_actual デフォルト
photo_size_select_actual モノクローム(白黒)
photo_size_select_actual Solarized風
photo_size_select_actual GitHub風(青ベース)
photo_size_select_actual Viva(黄緑ベース)
photo_size_select_actual Happy(紫ベース)
photo_size_select_actual Mint(緑ベース)
コードハイライトテーマ選択

明暗テーマごとに、コードハイライトのテーマを指定できます。

テーマ配色確認
スクリーン表示幅
640px
80%
90%
100%

768px以上の幅があるときのドキュメント部分表示幅です。

インデント
無し
1rem
2rem
3rem
原文確認
原文を全行表示
原文を一行ずつ表示
使用しない

※ 段落末のEボタンへカーソルオンで原文をPopupします。

Diff表示形式
色分けのみで区別
行頭の±で区別
削除線と追記で区別

※ [tl!…]形式の挿入削除行の表示形式です。

Pagination和文
ペジネーション
ペギネーション
ページネーション
ページ付け
Scaffold和文
スカフォールド
スキャフォールド
型枠生成
本文フォント

総称名以外はCSSと同様に、"〜"でエスケープしてください。

コードフォント

総称名以外はCSSと同様に、"〜"でエスケープしてください。

保存内容リセット

localStrageに保存してある設定項目をすべて削除し、デフォルト状態へ戻します。

ヘッダー項目移動

キーボード操作