ボム君.com

react で 「Warning: It looks like you're using a minified copy .....」のwarningを消す方法

warning内容

以下のwarningの消し方に結構詰まったので共有。

Warning: It looks like you're using a minified copy of the development build of React. When deploying React apps to production, make sure to use the production build which skips development warnings and is faster. See https://fb.me/react-minification for more details.

webpackbrowserify を使っている場合だと、公式サイトに対応方法が書いてあるが、 grunt を使っていて、対処法が載っていなく困った。

その公式サイトはここ

facebook.github.io

要するにproduction 用のbuildをしろと言うことなので、 いろいろ調べた結果、grunt-env というプラグインをいれて設定すれば解決できた。

手順

1, grunt-envのインストール

npm install --save-dev grunt-env

2, gruntfile.js でタスクを読み込む

grunt.loadNpmTasks('grunt-env');

3, gruntfile.js に記述を追加

grunt.initConfig({

...

env: {
    production: {
        NODE_ENV: 'production'
    }
},

...

});

4, gruntfile.js でタスクを登録する

grunt.registerTask('default', ['env:production', 'browserify']);

browserifyのタスクの前に実行する必要がある。

これでgruntを動かし直したら production 用のビルドになり、warningが消えました。

webpack で react, scss のコンパイルと ESLint を設定する方法

webpackとは

http://webpack.github.io

webpackは依存関係のあるJSやCSSなどを、まとめてくれるビルドツールです。

webpackにはLoaderという仕組みがあり、ソースコードに適用する処理を柔軟に設定することができ、 そのLoaderを使うことで、scssやJSXなどで書かれたファイルを変換することができます。

ここでは、react (jsx) , scss のコンパイルと、javascriptの構文をチェックしてくれるツールの ESLint をwebpackで行えるように設定します。

構成

今回は、以下のようなディレクトリ構成を想定し、
src の中の react と scss ファイルをdestディレクトリ内に配置することを考えます。

src
 ├─ react
 └─ scss
dest
 ├─ js
 └─ css
package.json
node_modules
webpack.config.js

gitを使用する場合は、node_modules をバージョン管理の対象外にしたいため、
src や dest と同じ階層に.gitignore を作成し、下記を記載します。

// .gitignore
node_modules/

webpackのインストール

package.jsonの作成

まずはprojectのpackageを管理するためのファイルである、
package.json を作成するために以下のコマンドを実行します。

$ npm init -y

-y オプションは聞かれる質問に全て yes でファイルを作成するというものです。
今回は全てyesで問題ないため、このオプションを実行します。

webpackのインストール

次に今回ビルドツールとして使用する webpack をインストールします。

$ npm install -D webpack

-D オプションは開発時にのみ必要なライブラリをインストールしつつ、
packpage.json に依存関係を記述してくれるオプションです。

scssのコンパイル設定

続いて scss のコンパイルのための設定を行います。

パッケージのインストール

$ npm install -D style-loader css-loader sass-loader node-sass extract-text-webpack-plugin

scssのコンパイルcssファイルとして出力する場合には extract-text-webpack-plugin というプラグインが必要になります。

webpack.config.js でビルド設定を書く

まずはwebpackの内容を記述するファイル webpack.config.js を作成し、
タスクを書いていきます。

// webpack.config.js
const ExtractTextPlugin = require('extract-text-webpack-plugin');

module.exports = {
  entry: {
    common: './src/scss/common.scss' // コンパイル対象ファイルのpath
  },
  output: {
    path: './dest/css/', // コンパイル後に出力するpath
    filename: '[name].css' // [name] には entry の key の値が入る(今回では common )
  },
  module: {
    loaders: [
      { 
        test: /\.scss$/,
        loader: ExtractTextPlugin.extract("style-loader", "css-loader?minimize!sass-loader")
      }
    ]
  },
  plugins: [
    new ExtractTextPlugin('[name].css')
  ]
}

"css-loader?minimize!sass-loader"?minimizeを外すと
ビルド結果がminifyされてない形で生成されます。

コンパイル実行

これで src/scss/common.scss を作成し、

$ ./node_modules/.bin/webpack -w

を実行すれば dest/css/common.css にビルド結果が生成されます。

reactのコンパイル設定

続いて react (JSX) のコンパイルの設定を行います。

babelのインストール

babelを使ってjsxファイルをトランスパイルします。

$ npm install -D babel-core babel-loader babel-preset-es2015 babel-preset-react

「babel-xxxxxx」というプラグインが多いですが、
babel-preset-xxxxx は、es2015 や JSX を変換するためのプリセットが babel 本体と分離しているので、個別にインストールする必要があります。

reactのインストール

実際に react をインストールします。

$ npm install -S react react-dom

-S オプションは、アプリケーションに必要なライブラリを、 packpage.json に追加しつつインストールをします。

webpack.config.js でビルド設定を書く

上で書いた webpack.config.js に reac tのビルドタスクを追加していきます。

// webpack.config.js
const ExtractTextPlugin = require('extract-text-webpack-plugin');

module.exports = [{
  // ここから react のコンパイルタスク
  entry: {
    app: './src/react/index.jsx',
  },
  output: {
    path: './dest/js/',
    filename: '[name].js'
  },
  module: {
    loaders: [
      { // babelの対象ファイルの指定
        test: /\.(js|jsx)$/,
        loader: 'babel',
        exclude: /node_modules/, // node_modules配下のファイルは対象外にする
        query: {
          presets: ["es2015", "react"],
        }
      },
    ]
  },
},{
  // ここから scss のコンパイルタスク
  entry: {
    common: './src/scss/common.scss'
  },
  output: {
    path: './dest/css/',
    filename: '[name].css'
  },
  module: {
    loaders: [
      { 
        test: /\.scss$/,
        loader: ExtractTextPlugin.extract("style-loader", "css-loader?minimize!sass-loader")
      }
    ]
  },
  plugins: [
    new ExtractTextPlugin('[name].css')
  ]
}]

コンパイル実行

これで src/react/index.jsx を作成し、

$ ./node_modules/.bin/webpack -w

を実行すれば dest/js/ に js のビルド結果が、 dest/css/css のビルド結果が生成されます。

ESLintを導入する

ESLintの設定方法についてはこちらに書いてあるので、参考にしてください。

ReactでESLintを使う - ログおきば

ここでは、ESLintの設定は完了していることを前提とし、
webpackでのビルド時にESLintを実行させる設定を行います。

ライブラリのインストール

まずはwebpackでESLintを使用するためのnpmのライブラリをインストールします

$ npm install -D eslint-loader

webpack.config.jsに記述

ESLintの組み込みもこれまでと同様に webppack.config.js 内に書いていきます。

const ExtractTextPlugin = require('extract-text-webpack-plugin');

module.exports = [{
  entry: {
    app: './assets/javascripts/app.jsx',
  },
  output: {
    path: '../app/assets/javascripts/',
    filename: '[name].js',
  },
  // eslint の設定ファイルの読み込み
  eslint: {
    configFile: './.eslintrc.json',
  },
  module: {
    loaders: [
      {
        test: /\.(js|jsx)$/,
        loader: 'babel',
        exclude: /node_modules/,
        query: {
          presets: ["es2015", "react"],
        }
      },
      // esLintの対象ファイルの指定
      {
        test: /\.(js|jsx)$/,
        loader: 'eslint',
        exclude: /node_modules/, // node_modules配下のファイルは対象外にする
      }
    ]
  },
},{
  .....

実行

実行コマンドはこれまでと同様、以下になります。

$ ./node_modules/.bin/webpack -w

Lintに引っかかった場合にはerrorログが表示されます。

サンプル

今回のサンプルはこちらにあります。参考にしてください。
GitHub - sottar/react_scss_compile_on_webpack_sample

ReactでESLintを使う

ESLintの導入

まずはnpmからESLintをインストール

$ npm install --save-dev eslint eslint-plugin-react

設定ファイルの生成

ESLint の魅力は、ルールを自由に設定出来ることです。
設定ファイルの生成は --init を使って設定ファイルを作成すると簡単です。

$ eslint --init

上のコマンドを実行すると対話形式で設定ファイルを作成できます。

$ ❯ Answer questions about your style 
$   Use a popular style guide 
$   Inspect your JavaScript file(s) 
  • Answer questions about your style
    AirBnBGoogleJavaScriptのスタイルガイドを使用できます。
  • Use a popular style guide
    対話形式でルールを作成していきます。

今回は Answer questions about your style を選択します。

すると以下の質問に1つずつ答えていくことになります

$ ? Are you using ECMAScript 6 features? Yes  
$ ? Are you using ES6 modules? Yes  
$ ? Where will your code run? Browser  
$ ? Do you use CommonJS? No  
$ ? Do you use JSX? Yes  
$ ? Do you use React Yes  
$ ? What style of indentation do you use?  Spaces  
$ ? What quotes do you use for strings? Single  
$ ? What line endings do you use? Unix  
$ ? Do you require semicolons? Yes  
$ ? What format do you want your config file to be in? JSON  

質問の後ろに書いてあるのが今回の私の入力です。
インデントやセミコロンなどの設定はお好みに応じて変更してください。

入力が完了すると、.eslintrc.json が以下のように生成されます

{
    "env": {
        "browser": true,
        "es6": true
    },
    "extends": "eslint:recommended",
    "parserOptions": {
        "ecmaFeatures": {
            "experimentalObjectRestSpread": true,
            "jsx": true
        },
        "sourceType": "module"
    },
    "plugins": [
        "react"
    ],
    "rules": {
        "indent": [
            "error",
            4
        ],
        "linebreak-style": [
            "error",
            "unix"
        ],
        "quotes": [
            "error",
            "single"
        ],
        "semi": [
            "error",
            "always"
        ]
    }
}

設定ファイルの修正

react/jsx-uses-vars を追加

ESLintは標準パッケージで jsx をサポートしてるのですが、
React の独自表記の部分はサポート外となっているため、
pluginを使用する必要があります。

  "rules": {
    "react/jsx-uses-vars": 1, // ← 追加
    "indent": [
      "error",
      2
    ],
    "linebreak-style": [
      "error",
   ......

github.com

ESLintの対象外のファイルを設定する

.eslintignore というファイルを作成することでESLintの対象外のファイルを指定できます。
node_modules ディレクトリ以下のファイルは対象外にしたいので設定します。

.eslintignore というファイルを作成し、以下を記述

node_modules/

ここまでの設定で使っても問題はないのですが、使いやすいように少し手を加えます。
必要に応じて変更してください。

インデントをスペース2つにする

デフォルトだとインデントがスペース4つになっているので、2つに変更します。

  "rules": {
    "indent": [
      "error",
      4
    ],
  .....

上を下に変更

  "rules": {
    "indent": [
      "error",
      2
    ],
  .....

jQqueryを使用する

Ajaxなどで jQuery を使用したい場合、 最初の設定ファイルだとjQueryの使用が許可されていないため、それを許可します。

  "env": {
    "browser": true,
    "es6": true
  },

上を下に変更

  "env": {
    "browser": true,
    "es6": true,
    "jquery": true
  },

最終的な形

最終的には .eslintrc.json ファイルは以下になります。

{
  "env": {
    "browser": true,
    "es6": true,
    "jquery": true
  },
  "extends": "eslint:recommended",
  "parserOptions": {
    "ecmaFeatures": {
      "experimentalObjectRestSpread": true,
      "jsx": true
    },
    "sourceType": "module"
  },
  "plugins": [
    "react"
  ],
  "rules": {
    "react/jsx-uses-vars": 1,
    "indent": [
      "error",
      2
    ],
    "linebreak-style": [
      "error",
      "unix"
    ],
    "quotes": [
      "error",
      "single"
    ],
    "semi": [
        "error",
        "always"
    ]
  }
}

実行方法

$ node_modules/.bin/eslint hoge.jsx

gulpやgrunt, webpack のビルド時に実行させることもできます。
実際にはこう言ったビルドツールと合わせて使うと思いますが、
記事が長くなってしまうのでまた別の記事に書きます。