LoginSignup
26
24

More than 5 years have passed since last update.

expressの既存プロジェクトをES6化する方法

Last updated at Posted at 2016-04-20

expressの既存プロジェクトをES6化する際に色々と手こずったのでメモ。

1.lebabを使って全てのjsファイルをES6に変換する。

・lebabをinstallする
npm install -g lebab
・lebabで全ファイルを変換する
lebab es5.js -o es6.js

lebab: http://lebab.io/

自動変換がうまくいっていっていない場合もあるので気をつける。
とくに、import、exportあたり。

2.babelでコンパイルできるようにする

そのままexpressを起動するとimportでエラーがでる。

/Users/hage/test/app.js:5
import express from 'express';
^^^^^^

SyntaxError: Unexpected reserved word
    at exports.runInThisContext (vm.js:53:16)
    at Module._compile (module.js:373:25)
    at Object.Module._extensions..js (module.js:416:10)
    at Module.load (module.js:343:32)
    at Function.Module._load (module.js:300:12)
    at Function.Module.runMain (module.js:441:10)
    at startup (node.js:139:18)
    at node.js:968:3

そこで、babelと利用しているPresetsをインストールする。
npm install babel --save
npm install babel-preset-es2015 --save ※es6の場合はこれ

presetsに関しては下記URLを参考
https://babeljs.io/docs/plugins/

3.各種設定ファイルを配置する

下記ファイルをルートディレクトリに作成してpresetsを指定。jshintrcも設定しておく。

.babelrc
{
  "presets": ["es2015"]
}
.jshintrc
{
    "esversion": 6
}

3.app.jsをラップする

ルートディレクトリにstart.jsを作成してapp.jsをラップする。

start.js
require('babel-register');
var app = require("./app.js");

package.jsonのstartも変更する

package.json
{
  "name": "sample-api",
  "version": "0.0.0",
  "private": true,
  "scripts": {
    "start": "node start.js"
  },
    :
}

4.expressを起動する

npm startで、変換が完了したexpressのプロジェクトを起動する。
※lebabの自動変換がうまくいっていない箇所はここでも発見できる。

参考
http://stackoverflow.com/questions/32346886/unexpected-reserved-word-import-in-node-js

26
24
0

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
26
24