improve support to read options from script tag data attr

This commit is contained in:
Moez Bouhlel
2014-10-22 18:00:33 +01:00
parent e5b18c08ce
commit 0681e59d3d
2 changed files with 24 additions and 7 deletions

View File

@@ -4,6 +4,7 @@
/*global window, document, location */
var less;
var addDataAttr = require("./utils").addDataAttr;
/*
TODO - options is now hidden - we should expose it on the less object, but not have it "as" the less object
@@ -15,13 +16,7 @@ var isFileProtocol = /^(file|chrome(-extension)?|resource|qrc|app):/.test(window
options = window.less || {};
// use options from the current script tag data attribues
var script = document.currentScript || (function() {
var scripts = document.getElementsByTagName("script");
return scripts[scripts.length - 1];
})();
for (var opt in script.dataset)
if(script.dataset.hasOwnProperty(opt))
options[opt] = script.dataset[opt];
options = addDataAttr(options);
// shim Promise if required
require('promise/polyfill.js');

View File

@@ -1,3 +1,4 @@
/* global document */
module.exports = {
extractId: function(href) {
return href.replace(/^[a-z-]+:\/+?[^\/]+/, '' ) // Remove protocol & domain
@@ -5,5 +6,26 @@ module.exports = {
.replace(/\.[a-zA-Z]+$/, '' ) // Remove simple extension
.replace(/[^\.\w-]+/g, '-') // Replace illegal characters
.replace(/\./g, ':'); // Replace dots with colons(for valid id)
},
addDataAttr: function(options) {
function reformatOptionName(option) {
return String.replace(option , /_(.)/g, function( match, p1) {
return p1.toUpperCase();
});
}
var script = document.currentScript || (function() {
var scripts = document.getElementsByTagName("script");
return scripts[scripts.length - 1];
})();
for (var opt in script.dataset)
if (script.dataset.hasOwnProperty(opt)) {
opt = reformatOptionName(opt);
if (opt === "env" || opt === "dumpLineNumbers" || opt === "rootpath" || opt === "errorReporting")
options[opt] = script.dataset[opt];
else
options[opt] = JSON.parse(script.dataset[opt]);
}
return options;
}
};