0
0

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.

Require.jsでJSTをモジュールとして読み込む

Last updated at Posted at 2017-02-01

概要

Gruntのプラグインgrunt-contrib-jstをインストール、require.jsから詠み込もうしたらうまくいかなかったので
解決方法と、その他調べたことを書く。

解決方法

結果から言うとJSTがAMDに対応していなかった (わけではないでしょう。 これは後述)
ので、require_config.jsに以下の記述を追加。

	paths: {
	    templates: [
		    '../jst/templates'
		]
	},
	shim : {
            templates: {
      	        exports: 'JST' // そのライブラリがグローバル変数として定義しているオブジェクトの名前を指定する
    	    },
	}

まとめると
・ shim で AMD に対応していないライブラリについての定義を記述する。
・ exports で、そのライブラリがグローバル変数として定義しているオブジェクトの名前を指定する。
・ require() による依存関係の解決のときには、ここで指定したオブジェクトが渡されることになる。

疑問点

・grunt-contrib-jstはAMD対応しているようです。このサイトで amd: trueというオプションが紹介されています。
以下のよう

module.exports = function(grunt) {

  grunt.initConfig({

    pkg: grunt.file.readJSON('package.json'),

    jst: {
      compile: {
        options: {
            //trueでdefine falseで通常
          amd: true,
          templateSettings: {
            interpolate : /\{\{(.+?)\}\}/g
          },
          processName: function(filename) {
            return filename.replace(/(src\/templates\/|.html)/g, '');
          }
        },
        files: {
          'src/javascripts/templates/templates.js': [
            'src/templates/**/*.html'
          ]
        }
      }
    },

    watch: {
      scripts: {
        files: ['src/templates/**/*.html'],
        tasks: ['jst'],
        options: {
          spawn: false,
        },
      },
    }

  });

  grunt.loadNpmTasks('grunt-contrib-jst');
  grunt.loadNpmTasks('grunt-contrib-watch');
}

試したけどうまくいかない。
多分Gruntfile.jsでのoptionsの記述方法が間違っているのか。(ちゃんと調べてないから)

*参考
このGistもJSTがうまく読み込めない問題について
言及している。

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?