2013-04-07 30 views
11

今天下午我一直在嘗試使用Grunt和Require JS。我是text模塊的忠實粉絲,並使用它來引入我的模板。在基於非Grunt的項目中,我使用了inlineTextstubModules要求使用JS選項來排列模板文件,並且效果很好。但是,我無法使用Grunt工作。內聯require.js文本!使用Grunt

需要配置

require.config({ 
    paths: { 
     // Using Bower for dependency management 
     text: '../components/requirejs-text/text' 
    } 
}); 

使用

define(['text!template.html'], function (html) { 
    // Do stuff with html 
}); 

Gruntfile.js

requirejs: { 
    dist: { 
     options: { 
      baseUrl: 'app/scripts', 
      optimize: 'none', 
      preserveLicenseComments: false, 
      useStrict: true, 
      wrap: true, 
      inlineText: true, 
      stubModules: ['text'] 
     } 
    } 
} 

運行後我在控制檯中的各種錯誤:

  • 一個未找到文件上/dist/components/requirejs-text/text.js
  • 一個Load timeout for modules: text!template.html_unnormalized2

兩個問題,那麼:

  • 這似乎並沒有被內聯(然後存根)text.js代碼
  • 它似乎沒有內聯template.html文件

任何想法爲什麼它不工作?

+0

什麼是您的文件夾結構是什麼樣子?執行時,你確定'text.js'在'dist'目錄嗎? – 2013-06-21 19:36:42

+0

我得到同樣的問題。對我來說,它看起來像構建工具正在尋找text.js,因爲單詞「text」出現在dependency ['text!template.html']中。我也在使用require文本插件。 – 2013-07-26 16:40:55

+0

你使用哪種require.js庫,因爲有很多? – ghost23 2013-08-14 09:56:22

回答

1

您看到錯誤,因爲您需要指示r.jstext模塊在哪裏。

你可以通過添加一個路徑配置:

requirejs: { 
    dist: { 
     options: { 
      baseUrl: 'app/scripts', 
      optimize: 'none', 
      preserveLicenseComments: false, 
      useStrict: true, 
      wrap: true, 
      inlineText: true, 
      stubModules: ['text'], 
      paths: { 
      'text': 'libs/text' // relative to baseUrl 
      } 
     } 
    } 
} 

然後,你需要將text.js模塊下載到相應的目錄。

但爲什麼你的require.config不工作?

因爲r.js需要在某個時刻評估配置。你沒有在你的require.config的問題提了,但要對其進行評估的情況下,你需要指明是r.js(見https://github.com/jrburke/r.js/blob/master/build/example.build.js#L35):

requirejs: { 
    dist: { 
     options: { 
      baseUrl: 'app/scripts', 
      optimize: 'none', 
      preserveLicenseComments: false, 
      useStrict: true, 
      wrap: true, 
      inlineText: true, 
      stubModules: ['text'], 
      mainConfigFile: '../config.js' // here is your require.config 

      // Optionally you can use paths to override the configuration 
      paths: { 
      'text': 'libs/text' // relative to baseUrl 
      } 
     } 
    } 
}