LoginSignup
2
2

More than 5 years have passed since last update.

gulp.jsでejsが動く環境をつくる

Last updated at Posted at 2018-09-10

環境

Mac

前提

npm がインストールされていること。
以前にインストールしたのをメモりました。
こちらも参考にしてください
▶︎nvmで、Node.jsとnpmのインストール(Mac)

方法

作業用ディレクトリに移動します
cd [作業用ディレクトリ]/

# init処理
npm init

# 必要パッケージをインストールします
npm install gulp --save
npm install gulp-ejs --save-dev

# gulpfile.js を作ります
touch gulpfile.js

# ソース用とコンパイル先のディレクトリを用意します
mkdir -p src/ejs dist/ejs

# 動作確認用にejsファイルを作成しておきます
echo 'hello ejs' > src/ejs/index.ejs

gulp.js

//gulpfile.jsに以下記載
const gulp = require('gulp');

gulp.task('ejs', function() { // タスク定義
    gulp.src(
        ['src/ejs/*.ejs', '!' + 'src/ejs/_*.ejs'] // _から始まるejsファイルを除外←★場合によっては各々設定してください
    )
        .pipe(gulp.dest('dist/ejs')); // 出力先←★場合によっては各々設定してください
});


# 動作させて、index.jsが誕生していることを確認
./node_modules/gulp/bin/gulp.js ejs

gulp.js

//ejsをhtmlにします
const gulp = require('gulp');
const ejs = require('gulp-ejs');//←★追加

gulp.task('ejs', function() { // タスク定義
    gulp.src(
        ['src/ejs/*.ejs', '!' + 'src/ejs/_*.ejs'] // _から始まるejsファイルを除外
    )
        .pipe(ejs({},{},{'ext': '.html'})) // 拡張子指定←★追加
        .pipe(gulp.dest('dist/ejs')); // 出力先
});


# 動作させて、index.htmlが誕生していることを確認
./node_modules/gulp/bin/gulp.js ejs

ハマったところ

1.gulpfile.jsに記載する際。
多くのサイトでは{}をひとつしか書いてないものがよく紹介されてました。
(度々変わるらしいです。)

gulp.js

//正しい
.pipe(ejs({},{},{'ext': '.html'})) // 拡張子指定

//間違い
.pipe(ejs({},{'ext': '.html'})) // 拡張子指定

2.node_moduleで足りないモジュールがあったので以下の手順で追加

npm install -g npm-install-missing
npm-install-missing
2
2
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
2
2