Set lodash / underscore template settings globally using require.js

后端 未结 3 1477
被撕碎了的回忆
被撕碎了的回忆 2020-12-24 03:54

Is there a way to set the templateSettings for lodash when using RequireJS?

Right now in my main startup I have,

  require([\'lodash\',          


        
3条回答
  •  温柔的废话
    2020-12-24 04:27

    Bear in mind that if you're using underscore >=1.6.0 or lodash-amd the solution is pretty simple:

    "main.js" configuration file

    require.config({
      baseUrl: './', // Your base URL
      paths: {
        // Path to a module you create that will require the underscore module.
        // You cannot use the "underscore" name since underscore.js registers "underscore" as its module name.
        // That's why I use "_".
        _: 'underscore',
    
       // Path to underscore module 
       underscore: '../../bower_components/underscore/underscore',
      }
    });
    

    Your "_.js" file:

    define(['underscore'], function(_) {
    
      // Here you can manipulate/customize underscore.js to your taste.
      // For example: I usually add the "variable" setting for templates
      // here so that it's applied to all templates automatically.
    
      // Add "variable" property so templates are able to render faster!
      // @see http://underscorejs.org/#template
      _.templateSettings.variable = 'data';
    
      return _;
    });
    

    A module file. It requires our "_" module which requires "underscore" and patches it.

    define(['_'], function(_){
      // You can see the "variable" property is there
      console.log(_.templateSettings);   
    });
    

提交回复
热议问题