22
22

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.

[Node.js]ES6仕様で動くようにする

Last updated at Posted at 2018-02-18

わりと出尽くされているネタのような気がしますが、メモも兼ねて書きます。
発端としては、下記のようにUnexpected token exportと出たことです。

> hoge@1.0.0 start /Users/fuga/my_pj/hoge/src
> node app.js

/Users/fuga/my_pj/hoge/src/modules/Piyo.js:1
(function (exports, require, module, __filename, __dirname) { export class Piyo
                                                              ^^^^^^

SyntaxError: Unexpected token export
    at createScript (vm.js:80:10)
    at Object.runInThisContext (vm.js:139:10)
    at Module._compile (module.js:607:28)
    at Object.Module._extensions..js (module.js:654:10)
    at Module.load (module.js:556:32)
    at tryModuleLoad (module.js:499:12)
    at Function.Module._load (module.js:491:3)
    at Module.require (module.js:587:17)
    at require (internal/module.js:11:18)
    at Object.<anonymous> (/Users/fuga/my_pj/hoge/src/app.js:3:20)

基本的には下記のリンクに従って書きます。
babel/example-node-server: Example Node Server w/ Babel

ディレクトリ構成

root/
 ├ app/
 │ └ app.js
 ├ dist/
 ├ node_modules/
 └ package.json

手順

①必要なパッケージのインストール

$ npm install --save-dev babel-cli
$ npm install --save-dev babel-preset-env

最初、ES2015の機能だけ使えればよいかと思ってnpm install --save-dev babel-preset-es2015と書いていましたが、

npm WARN deprecated babel-preset-es2015@6.24.1: 🙌  Thanks for using Babel: we recommend using babel-preset-env now: please read babeljs.io/env to update!

とのエラーが出たので、babel-preset-envに変えました。

②package.jsonに追記

  "scripts": {
+   "start": "babel-node app/app.js --presets babel-preset-env -x js,json"
+   "build": "babel app -d dist --presets babel-preset-env --copy-files",
+   "serve": "node dist/app.js"
  }

完成。
これで下記のコマンドが使えるようになります。

$ npm start // 開発用のコマンド
$ npm run build // Releaseビルド
$ npm run serve // Releaseビルドしたものを起動
22
22
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
22
22

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?