2011-05-04 5 views
10

적은 수의 코드를 컴파일하는 데 클라이언트 쪽 JavaScript 버전을 사용하고 있으며 최종 라이브 사이트에서도이 코드를 계속 사용하고 싶습니다. 사용자가 몇 가지 변수를 커스터마이징 할 수있게 해주는 기능과 한번에로드되지 않는 웹 애플리케이션 인 "테마"를 전체 앱에서 볼 수있는 능력은 컴파일 시간을 줄이기 위해로드 시간이 추가로 필요하다고 생각합니다. 허용됨).requireJS and LESS

나는 또한 requireJS를 사용하고있다.

질문은 :

A) 어떻게 적은 코드를로드 requireJS을받을 수 있나요?

B) 컴파일이 완료 될 때 이벤트가 덜 발송됩니까? 및

C) 명령에 따라 다시 컴파일하려면 트리거하는 방법이 있습니까?

감사합니다.

답변

14

내가 다음 텍스트를 구문 분석하는 새로운 less.Parser 인스턴스를 생성, 텍스트로 .less 파일을로드 할 RequireJS의 text loader plugin을 사용한 후, 자신은 스타일의 텍스트를 추가 :

(new less.Parser()).parse(lessText, function (err, css) { 
    if (err) { 
    if (typeof console !== 'undefined' && console.error) { 
     console.error(err); 
    } 
    } else { 
    var style = document.createElement('style'); 
    style.type = 'text/css'; 
    style.textContent = css.toCSS(); 
    } 
}); 

당신이 걸릴 수 있습니다 비슷한 방식이지만 스타일 노드에 ID를 부여하고 해당 ID를 제거한 다음 필요할 때 다시 구문 분석 된 덜 텍스트를 다시 추가하십시오.

주의 사항 : 텍스트 플러그인은 텍스트 파일이 웹 페이지와 동일한 도메인에있을 때 텍스트 파일을 필요할 때만로드 할 수 있습니다. RequireJS 옵티 마이저를 사용하면 텍스트를 내장 된 최적화 된 JS 파일로 인라인 할 수 있습니다.

+1

lessText에 @imports가있는 경우 어떻게 작동합니까? 우리는 여러 개의 파일을 requirejs 텍스트 모듈에 매핑하려고합니다 ... 가능합니까? 아무도 그것을 시험해 보지 않았습니까? – Rafael

+0

안녕하세요 @jrburke, 귀하의 회신에 감사드립니다 requirejs 덜 스타일을 처리하기 위해 littele 라이브러리를 만들었습니다 https://github.com/pingsrl/requirejs-less – wezzy

10

@jrburke은 : 코드에 내가 조립 한 빠른 requirejs을 기반으로 플러그인이 :

define({ 

    version: '0.1', 

    load: function(name, req, onLoad, config) { 

     req(['text!' + name, 'base/less'], function(lessText) { 

      var styleElem; 

      (new less.Parser()).parse(lessText, function (err, css) { 
       if (err) { 
        if (typeof console !== 'undefined' && console.error) { 
         console.error(err); 
        } 
       } else { 
        styleElem = document.createElement('style'); 
        styleElem.type = 'text/css'; 

        if (styleElem.styleSheet) 
         styleElem.styleSheet.cssText = css.toCSS(); 
        else 
         styleElem.appendChild(document.createTextNode(css.toCSS())); 

        document.getElementsByTagName("head")[0].appendChild(styleElem); 
       } 

       onLoad(styleElem); 
      }); 

     });  
    } 

}); 

"기본/이하"포인트를 덜 소스. 당신은 또한 이것을 미리로드 할 수 있으며, 글로벌 less 오브젝트가 있다고 가정합니다. 이상적으로, 나는 더 적은 Parser 객체를이 플러그인 자체로 가져 와서 전역을 전혀 만들지 않기를 바란다.

처럼 물건을 할 수있는이 사용 :

require(['less!global.less'], function(elem) { 

}); 

하는 시점에서, global.less 구문 분석되었으며 페이지에 추가 내가 제거하거나해야 할 경우 스타일 요소를 가리키는 ELEM를 다시 제공 어떤 이유로 그것을 수정하십시오.

아무에게도 의견이 있거나 더 좋은 방법을 알고 있습니까? @nicholas는 수입과 플러그인으로

건배

+0

안녕하세요 nicholas jrburke 및 귀하의 회신에 감사드립니다이 라이브러리를 만들었습니다. https://github.com/pingsrl/requirejsless – wezzy

3

나는 문제가되었다. 검색 경로에 파일의 경로를 추가하고 파일 이름을 설정하여 오류 메시지를 해결했습니다.

// http://stackoverflow.com/questions/5889901/requirejs-and-less 
// enables require(['share/less!whatever.less'], function(elem) {}); 
define({ 
    version: '0.1', 
    load: function(name, req, onLoad, config) { 
     req(['share/text!' + name, 'share/less-1.3.0'], function(lessText) { 
      var styleElem; 
      var parser = new(less.Parser)({ 
       filename: name, 
       paths: [name.split('/').slice(0,-1).join('/') + '/'], 
      }); 
      parser.parse(lessText, function (err, css) { 
       if (err) { 
        if (typeof console !== 'undefined' && console.error) { 
         console.error(err); 
        } 
       } else { 
        styleElem = document.createElement('style'); 
        styleElem.type = 'text/css'; 

        if (styleElem.styleSheet) 
         styleElem.styleSheet.cssText = css.toCSS(); 
        else 
         styleElem.appendChild(document.createTextNode(css.toCSS())); 

        document.getElementsByTagName("head")[0].appendChild(styleElem); 
       } 
       onLoad(styleElem); 
      }); 
     }); 
    } 
}); 
관련 문제