This commit is contained in:
yyh931018@qq.com
2022-09-08 15:32:32 +08:00
commit 1b0c8f4196
4714 changed files with 974427 additions and 0 deletions

View File

@@ -0,0 +1,22 @@
{
"name": "require-css",
"version": "0.1.10",
"ignore": [
"example",
"test",
".gitignore"
],
"main": [
"css.js"
],
"homepage": "https://github.com/guybedford/require-css",
"_release": "0.1.10",
"_resolution": {
"type": "version",
"tag": "0.1.10",
"commit": "c421807c3fed889e61a086c6442ae065ed0cb67a"
},
"_source": "https://github.com/guybedford/require-css.git",
"_target": "~0.1.8",
"_originalSource": "require-css"
}

View File

@@ -0,0 +1,5 @@
[*]
indent_style = space
indent_size = 2
#trim_trailing_whitespace = true
insert_final_newline = true

View File

@@ -0,0 +1,6 @@
{
"js": {
"indent_char": " ",
"indent_size": 2
}
}

View File

@@ -0,0 +1,10 @@
MIT License
-----------
Copyright (C) 2013 Guy Bedford
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View File

@@ -0,0 +1,250 @@
require-css
===========
RequireJS CSS requiring and optimization, with almond support.
Useful for writing modular CSS dependencies alongside scripts.
For LESS inclusion, use [require-less](https://github.com/guybedford/require-less), which behaves and builds the css exactly like this module apart from the preprocessing step.
<a href="https://www.gittip.com/guybedford/"><img src="http://img.shields.io/gittip/guybedford.svg" /></a>
Overview
--------
Allows the construction of scripts that can require CSS, using the simple RequireJS syntax:
```javascript
define(['css!styles/main'], function() {
//code that requires the stylesheet: styles/main.css
});
```
Fully compatible in IE 6+, Chrome 3+, Firefox 3.5+, Opera 10+, iOS.
* **CSS builds** When run as part of a build with the RequireJS optimizer, `css!` dependencies are automatically inlined into the built layer within the JavaScript, fully compatible with layering. CSS injection is performed as soon as the layer is loaded.
* **Option to build separate layer CSS files** A `separateCSS` build parameter allows for built layers to output their css files separately, instead of inline with the JavaScript, for manual inclusion.
* **CSS compression** CSS redundancy compression is supported through the external library, [csso](https://github.com/css/csso).
Installation and Setup
----------------------
Download the require-css folder manually or use Bower:
```bash
bower install require-css
```
To allow the direct `css!` usage, add the following [map configuration](http://requirejs.org/docs/api.html#config-map) in RequireJS:
```javascript
map: {
'*': {
'css': 'require-css/css' // or whatever the path to require-css is
}
}
```
Use Cases and Benefits
----------------------
### Motivation
The use case for RequireCSS came out of a need to manage templates and their CSS together.
The idea being that a CSS require can be a dependency of the code that dynamically renders a template.
When writing a large dynamic application, with templates being rendered on the client-side, it can be beneficial to inject the CSS as templates are required instead
of dumping all the CSS together separately. The added benefit of this is then being able to build the CSS naturally with the RequireJS optimizer,
which also supports [separate build layers](http://requirejs.org/docs/1.0/docs/faq-optimization.html#priority) as needed.
### Script-inlined CSS Benefits
By default, during the build CSS is compressed and inlined as a string within the layer that injects the CSS when run.
If the layer is included as a `<script>` tag, only one browser request is needed instead of many separate CSS requests with `<link>` tags.
Even better than including a layer as a `<script>` tag is to include the layer dynamically with a non-blocking require.
Then the page can be displayed while the layer is still loading asynchronously in the background.
In this case, the CSS that goes with a template being dynamically rendered is loaded with that same script asynchronously.
No longer does it need to sit in a `<link>` tag that blocks the page display unnecessarily.
Modular CSS
-----------
RequireCSS implies a CSS modularisation where styles can be scoped directly to the render code that they are bundled with.
Just like JS requires, the order of CSS injection can't be guaranteed. The idea here is that whenever there are style overrides, they should
be based on using a more specific selector with an extra id or class at the base, and not assuming a CSS load order. Reset and global styles are a repeated dependency of all
modular styles that build on top of them.
Optimizer Configuration
-----------------------
### Basic Usage
Optimizer configuration:
```javascript
{
modules: [
{
name: 'mymodule',
exclude: ['css/normalize']
}
]
}
```
If the contents of 'mymodule' are:
```javascript
define(['css!style', 'css!page'], function(css) {
//...
});
```
Then the optimizer output would be:
-mymodule.js containing:
style.css and page.css which will be dynamically injected
The `css/normalize` exclude is needed due to [r.js issue #289](https://github.com/jrburke/r.js/issues/289)
### Separate File Output
To output the CSS to a separate file, use the configuration:
```javascript
{
separateCSS: true,
modules: [
{
name: 'mymodule'
}
]
}
```
This will then output all the css to the file `mymodule.css`. This configuration can also be placed on the module object itself for layer-specific settings.
Optimization is fully compatible with exclude and include.
### IE8 and 9 Selector Limit
In IE9 and below, there is a maximum limit of 4095 selectors per stylesheet.
In order to avoid this limit, CSS concatenation can be disabled entirely with the `IESelectorLimit` option.
```javascript
{
IESelectorLimit: true,
modules: [
{
name: 'mymodule'
}
]
}
```
Ideally build layers would avoid this limit entirely by naturally being designed to not reach it. This option is really only as a fix when nothing else
is possible as it will degrade injection performance.
This option is also not compatible with the `separateCSS` option.
### Excluding the CSS Module in Production
When dynamic CSS requires are not going to be made in production, a minimal version of RequireCSS can be written by setting a pragma for the build:
```javascript
{
pragmasOnSave: {
excludeRequireCss: true
}
}
```
### siteRoot Configuration
When building the CSS, all URIs are renormalized relative to the site root.
It assumed that the siteRoot matches the build directory in this case.
If this is different, then specify the server path of the siteRoot relative to the baseURL in the configuration.
For example, if the site root is `www` and we are building the directory `www/lib`, we would use the configuration:
```javascript
{
appDir: 'lib',
dir: 'lib-built',
siteRoot: '../',
modules: [
{
name: 'mymodule'
}
]
}
```
### Almond Configuration
Almond doesn't support the `packages` configuration option. When using Almond, rather configuration RequireCSS with map configuration instead, by including the following configuration in the production app:
```javascript
requirejs.config({
map: {
'*': {
css: 'require-css/css'
}
}
});
```
### Disabling the Build
To disable any CSS build entirely, use the configuration option `buildCSS`:
```javascript
{
buildCSS: false,
modules: [
{
name: 'mymodule'
}
]
}
```
CSS requires will then be left in the source "as is". This shouldn't be used with `stubModules`.
CSS Compression
---------------
CSS compression is supported with [csso](https://github.com/css/csso).
To enable the CSS compression, install csso with npm:
```
npm install csso -g
```
The build log will display the compression results.
When running the r.js optimizer through NodeJS, sometimes the global module isn't found. In this case install csso as a local node module so it can be found.
Injection methods
-----------------
When loading a CSS file or external CSS file, a `<link>` tag is used. Cross-browser support comes through a number of careful browser conditions for this.
If CSS resources such as images are important to be loaded first, these can be added to the require through a loader plugin that can act as a preloader such as [image](https://github.com/millermedeiros/requirejs-plugins) or [font](https://github.com/millermedeiros/requirejs-plugins). Then a require can be written of the form:
```javascript
require(['css!my-css', 'image!preload-background-image.jpg', 'font!google,families:[Tangerine]']);
```
License
---
MIT

View File

@@ -0,0 +1,6 @@
{
"name": "require-css",
"version": "0.1.10",
"ignore": ["example", "test", ".gitignore"],
"main": ["css.js"]
}

View File

@@ -0,0 +1,46 @@
#!/bin/bash
# To cover all possible use case, you should change `optimizeCss` in `example/build.js` from "none" to
# optimizeCss: "standard.keepLines"
# optimizeCss: "standard.keepWhitespace"
# optimizeCss: "standard.keepComments"
# optimizeCss: "standard.keepComments.keepLines"
# optimizeCss: "standard.keepLines.keepWhitespace" - default by r.js
(
npm install requirejs@2.1.10 -g
npm install csso@1.3.12 -g
r.js -o example/build.js
npm install csso@1.4.0 -g
r.js -o example/build.js
npm install csso@1.8.0 -g
r.js -o example/build.js
npm install csso@2.0.0 -g
r.js -o example/build.js
npm install csso@latest -g
r.js -o example/build.js
# RequireJS@latest
npm install requirejs@latest -g
npm install csso@1.3.12 -g
r.js -o example/build.js
npm install csso@1.4.0 -g
r.js -o example/build.js
npm install csso@1.8.0 -g
r.js -o example/build.js
npm install csso@2.0.0 -g
r.js -o example/build.js
npm install csso@latest -g
r.js -o example/build.js
) > compatibility.log

View File

@@ -0,0 +1,244 @@
define(['require', './normalize'], function(req, normalize) {
var cssAPI = {};
var isWindows = !!process.platform.match(/^win/);
function compress(css) {
if (config.optimizeCss == 'none') {
return css;
}
if (typeof process !== "undefined" && process.versions && !!process.versions.node && require.nodeRequire) {
try {
var csso = require.nodeRequire('csso');
}
catch(e) {
console.log('Compression module not installed. Use "npm install csso -g" to enable.');
return css;
}
var csslen = css.length;
try {
if (typeof csso.minify === 'function') {
var minifyResult = csso.minify(css);
if (typeof minifyResult === 'string'){ // for csso < 2.0.0
css = minifyResult;
} else if (typeof minifyResult === 'object'){ // for csso >= 2.0.0
css = minifyResult.css;
}
} else { // justDoIt() was always. minify() appeared in csso 1.4.0.
css = csso.justDoIt(css);
}
}
catch(e) {
console.log('Compression failed due to a CSS syntax error.');
return css;
}
console.log('Compressed CSS output to ' + Math.round(css.length / csslen * 100) + '%.');
return css;
}
console.log('Compression not supported outside of nodejs environments.');
return css;
}
//load file code - stolen from text plugin
function loadFile(path) {
if (typeof process !== "undefined" && process.versions && !!process.versions.node && require.nodeRequire) {
var fs = require.nodeRequire('fs');
var file = fs.readFileSync(path, 'utf8');
if (file.indexOf('\uFEFF') === 0)
return file.substring(1);
return file;
}
else {
var file = new java.io.File(path),
lineSeparator = java.lang.System.getProperty("line.separator"),
input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(file), 'utf-8')),
stringBuffer, line;
try {
stringBuffer = new java.lang.StringBuffer();
line = input.readLine();
if (line && line.length() && line.charAt(0) === 0xfeff)
line = line.substring(1);
stringBuffer.append(line);
while ((line = input.readLine()) !== null) {
stringBuffer.append(lineSeparator).append(line);
}
return String(stringBuffer.toString());
}
finally {
input.close();
}
}
}
function saveFile(path, data) {
if (typeof process !== "undefined" && process.versions && !!process.versions.node && require.nodeRequire) {
var fs = require.nodeRequire('fs');
fs.writeFileSync(path, data, 'utf8');
}
else {
var content = new java.lang.String(data);
var output = new java.io.BufferedWriter(new java.io.OutputStreamWriter(new java.io.FileOutputStream(path), 'utf-8'));
try {
output.write(content, 0, content.length());
output.flush();
}
finally {
output.close();
}
}
}
//when adding to the link buffer, paths are normalised to the baseUrl
//when removing from the link buffer, paths are normalised to the output file path
function escape(content) {
return content.replace(/(["'\\])/g, '\\$1')
.replace(/[\f]/g, "\\f")
.replace(/[\b]/g, "\\b")
.replace(/[\n]/g, "\\n")
.replace(/[\t]/g, "\\t")
.replace(/[\r]/g, "\\r");
}
// NB add @media query support for media imports
var importRegEx = /@import\s*(url)?\s*(('([^']*)'|"([^"]*)")|\(('([^']*)'|"([^"]*)"|([^\)]*))\))\s*;?/g;
var absUrlRegEx = /^([^\:\/]+:\/)?\//;
// Write Css module definition
var writeCSSDefinition = "define('@writecss', function() {return function writeCss(c) {var d=document,a='appendChild',i='styleSheet',s=d.createElement('style');s.type='text/css';d.getElementsByTagName('head')[0][a](s);s[i]?s[i].cssText=c:s[a](d.createTextNode(c));};});";
var siteRoot;
var baseParts = req.toUrl('base_url').split('/');
baseParts[baseParts.length - 1] = '';
var baseUrl = baseParts.join('/');
var curModule = 0;
var config;
var writeCSSForLayer = true;
var layerBuffer = [];
var cssBuffer = {};
cssAPI.load = function(name, req, load, _config) {
//store config
config = config || _config;
if (!siteRoot) {
siteRoot = path.resolve(config.dir || path.dirname(config.out), config.siteRoot || '.') + '/';
if (isWindows)
siteRoot = siteRoot.replace(/\\/g, '/');
}
//external URLS don't get added (just like JS requires)
if (name.match(absUrlRegEx))
return load();
var fileUrl = req.toUrl(name + '.css');
if (isWindows)
fileUrl = fileUrl.replace(/\\/g, '/');
// rebase to the output directory if based on the source directory;
// baseUrl points always to the output directory, fileUrl only if
// it is not prefixed by a computed path (relative too)
var fileSiteUrl = fileUrl;
if (fileSiteUrl.indexOf(baseUrl) < 0) {
var appRoot = req.toUrl(config.appDir);
if (isWindows)
appRoot = appRoot.replace(/\\/g, '/');
if (fileSiteUrl.indexOf(appRoot) == 0)
fileSiteUrl = siteRoot + fileSiteUrl.substring(appRoot.length);
}
//add to the buffer
cssBuffer[name] = normalize(loadFile(fileUrl), fileSiteUrl, siteRoot);
load();
}
cssAPI.normalize = function(name, normalize) {
if (name.substr(name.length - 4, 4) == '.css')
name = name.substr(0, name.length - 4);
return normalize(name);
}
cssAPI.write = function(pluginName, moduleName, write, parse) {
var cssModule;
//external URLS don't get added (just like JS requires)
if (moduleName.match(absUrlRegEx))
return;
layerBuffer.push(cssBuffer[moduleName]);
if (!global._requirejsCssData) {
global._requirejsCssData = {
usedBy: {css: true},
css: ''
}
} else {
global._requirejsCssData.usedBy.css = true;
}
if (config.buildCSS != false) {
var style = cssBuffer[moduleName];
if (config.writeCSSModule && style) {
if (writeCSSForLayer) {
writeCSSForLayer = false;
write(writeCSSDefinition);
}
cssModule = 'define(["@writecss"], function(writeCss){\n writeCss("'+ escape(compress(style)) +'");\n})';
}
else {
cssModule = 'define(function(){})';
}
write.asModule(pluginName + '!' + moduleName, cssModule);
}
}
cssAPI.onLayerEnd = function(write, data) {
if (config.separateCSS && config.IESelectorLimit)
throw 'RequireCSS: separateCSS option is not compatible with ensuring the IE selector limit';
if (config.separateCSS) {
var outPath = data.path.replace(/(\.js)?$/, '.css');
console.log('Writing CSS! file: ' + outPath + '\n');
var css = layerBuffer.join('');
process.nextTick(function() {
if (global._requirejsCssData) {
css = global._requirejsCssData.css = css + global._requirejsCssData.css;
delete global._requirejsCssData.usedBy.css;
if (Object.keys(global._requirejsCssData.usedBy).length === 0) {
delete global._requirejsCssData;
}
}
saveFile(outPath, compress(css));
});
}
else if (config.buildCSS != false && config.writeCSSModule != true) {
var styles = config.IESelectorLimit ? layerBuffer : [layerBuffer.join('')];
for (var i = 0; i < styles.length; i++) {
if (styles[i] == '')
return;
write(
"(function(c){var d=document,a='appendChild',i='styleSheet',s=d.createElement('style');s.type='text/css';d.getElementsByTagName('head')[0][a](s);s[i]?s[i].cssText=c:s[a](d.createTextNode(c));})\n"
+ "('" + escape(compress(styles[i])) + "');\n"
);
}
}
//clear layer buffer for next layer
layerBuffer = [];
writeCSSForLayer = true;
}
return cssAPI;
});

View File

@@ -0,0 +1,169 @@
/*
* Require-CSS RequireJS css! loader plugin
* 0.1.10
* Guy Bedford 2014
* MIT
*/
/*
*
* Usage:
* require(['css!./mycssFile']);
*
* Tested and working in (up to latest versions as of March 2013):
* Android
* iOS 6
* IE 6 - 10
* Chrome 3 - 26
* Firefox 3.5 - 19
* Opera 10 - 12
*
* browserling.com used for virtual testing environment
*
* Credit to B Cavalier & J Hann for the IE 6 - 9 method,
* refined with help from Martin Cermak
*
* Sources that helped along the way:
* - https://developer.mozilla.org/en-US/docs/Browser_detection_using_the_user_agent
* - http://www.phpied.com/when-is-a-stylesheet-really-loaded/
* - https://github.com/cujojs/curl/blob/master/src/curl/plugin/css.js
*
*/
define(function() {
//>>excludeStart('excludeRequireCss', pragmas.excludeRequireCss)
if (typeof window == 'undefined')
return { load: function(n, r, load){ load() } };
var head = document.getElementsByTagName('head')[0];
var engine = window.navigator.userAgent.match(/Trident\/([^ ;]*)|AppleWebKit\/([^ ;]*)|Opera\/([^ ;]*)|rv\:([^ ;]*)(.*?)Gecko\/([^ ;]*)|MSIE\s([^ ;]*)|AndroidWebKit\/([^ ;]*)/) || 0;
// use <style> @import load method (IE < 9, Firefox < 18)
var useImportLoad = false;
// set to false for explicit <link> load checking when onload doesn't work perfectly (webkit)
var useOnload = true;
// trident / msie
if (engine[1] || engine[7])
useImportLoad = parseInt(engine[1]) < 6 || parseInt(engine[7]) <= 9;
// webkit
else if (engine[2] || engine[8] || 'WebkitAppearance' in document.documentElement.style)
useOnload = false;
// gecko
else if (engine[4])
useImportLoad = parseInt(engine[4]) < 18;
//>>excludeEnd('excludeRequireCss')
//main api object
var cssAPI = {};
//>>excludeStart('excludeRequireCss', pragmas.excludeRequireCss)
cssAPI.pluginBuilder = './css-builder';
// <style> @import load method
var curStyle, curSheet;
var createStyle = function () {
curStyle = document.createElement('style');
head.appendChild(curStyle);
curSheet = curStyle.styleSheet || curStyle.sheet;
}
var ieCnt = 0;
var ieLoads = [];
var ieCurCallback;
var createIeLoad = function(url) {
curSheet.addImport(url);
curStyle.onload = function(){ processIeLoad() };
ieCnt++;
if (ieCnt == 31) {
createStyle();
ieCnt = 0;
}
}
var processIeLoad = function() {
ieCurCallback();
var nextLoad = ieLoads.shift();
if (!nextLoad) {
ieCurCallback = null;
return;
}
ieCurCallback = nextLoad[1];
createIeLoad(nextLoad[0]);
}
var importLoad = function(url, callback) {
if (!curSheet || !curSheet.addImport)
createStyle();
if (curSheet && curSheet.addImport) {
// old IE
if (ieCurCallback) {
ieLoads.push([url, callback]);
}
else {
createIeLoad(url);
ieCurCallback = callback;
}
}
else {
// old Firefox
curStyle.textContent = '@import "' + url + '";';
var loadInterval = setInterval(function() {
try {
curStyle.sheet.cssRules;
clearInterval(loadInterval);
callback();
} catch(e) {}
}, 10);
}
}
// <link> load method
var linkLoad = function(url, callback) {
var link = document.createElement('link');
link.type = 'text/css';
link.rel = 'stylesheet';
if (useOnload)
link.onload = function() {
link.onload = function() {};
// for style dimensions queries, a short delay can still be necessary
setTimeout(callback, 7);
}
else
var loadInterval = setInterval(function() {
for (var i = 0; i < document.styleSheets.length; i++) {
var sheet = document.styleSheets[i];
if (sheet.href == link.href) {
clearInterval(loadInterval);
return callback();
}
}
}, 10);
link.href = url;
head.appendChild(link);
}
//>>excludeEnd('excludeRequireCss')
cssAPI.normalize = function(name, normalize) {
if (name.substr(name.length - 4, 4) == '.css')
name = name.substr(0, name.length - 4);
return normalize(name);
}
//>>excludeStart('excludeRequireCss', pragmas.excludeRequireCss)
cssAPI.load = function(cssId, req, load, config) {
(useImportLoad ? importLoad : linkLoad)(req.toUrl(cssId + '.css'), load);
}
//>>excludeEnd('excludeRequireCss')
return cssAPI;
});

View File

@@ -0,0 +1 @@
define(function(){if("undefined"==typeof window)return{load:function(a,b,c){c()}};var a=document.getElementsByTagName("head")[0],b=window.navigator.userAgent.match(/Trident\/([^ ;]*)|AppleWebKit\/([^ ;]*)|Opera\/([^ ;]*)|rv\:([^ ;]*)(.*?)Gecko\/([^ ;]*)|MSIE\s([^ ;]*)|AndroidWebKit\/([^ ;]*)/)||0,c=!1,d=!0;b[1]||b[7]?c=parseInt(b[1])<6||parseInt(b[7])<=9:b[2]||b[8]?d=!1:b[4]&&(c=parseInt(b[4])<18);var e={};e.pluginBuilder="./css-builder";var f,g,h,i=function(){f=document.createElement("style"),a.appendChild(f),g=f.styleSheet||f.sheet},j=0,k=[],l=function(a){g.addImport(a),f.onload=function(){m()},j++,31==j&&(i(),j=0)},m=function(){h();var a=k.shift();return a?(h=a[1],void l(a[0])):void(h=null)},n=function(a,b){if(g&&g.addImport||i(),g&&g.addImport)h?k.push([a,b]):(l(a),h=b);else{f.textContent='@import "'+a+'";';var c=setInterval(function(){try{f.sheet.cssRules,clearInterval(c),b()}catch(a){}},10)}},o=function(b,c){var e=document.createElement("link");if(e.type="text/css",e.rel="stylesheet",d)e.onload=function(){e.onload=function(){},setTimeout(c,7)};else var f=setInterval(function(){for(var a=0;a<document.styleSheets.length;a++){var b=document.styleSheets[a];if(b.href==e.href)return clearInterval(f),c()}},10);e.href=b,a.appendChild(e)};return e.normalize=function(a,b){return".css"==a.substr(a.length-4,4)&&(a=a.substr(0,a.length-4)),b(a)},e.load=function(a,b,d,e){(c?n:o)(b.toUrl(a+".css"),d)},e});

View File

@@ -0,0 +1,141 @@
//>>excludeStart('excludeRequireCss', pragmas.excludeRequireCss)
/*
* css.normalize.js
*
* CSS Normalization
*
* CSS paths are normalized based on an optional basePath and the RequireJS config
*
* Usage:
* normalize(css, fromBasePath, toBasePath);
*
* css: the stylesheet content to normalize
* fromBasePath: the absolute base path of the css relative to any root (but without ../ backtracking)
* toBasePath: the absolute new base path of the css relative to the same root
*
* Absolute dependencies are left untouched.
*
* Urls in the CSS are picked up by regular expressions.
* These will catch all statements of the form:
*
* url(*)
* url('*')
* url("*")
*
* @import '*'
* @import "*"
*
* (and so also @import url(*) variations)
*
* For urls needing normalization
*
*/
define(function() {
// regular expression for removing double slashes
// eg http://www.example.com//my///url/here -> http://www.example.com/my/url/here
var slashes = /([^:])\/+/g
var removeDoubleSlashes = function(uri) {
return uri.replace(slashes, '$1/');
}
// given a relative URI, and two absolute base URIs, convert it from one base to another
var protocolRegEx = /[^\:\/]*:\/\/([^\/])*/;
var absUrlRegEx = /^(\/|data:)/;
function convertURIBase(uri, fromBase, toBase) {
if (uri.match(absUrlRegEx) || uri.match(protocolRegEx))
return uri;
uri = removeDoubleSlashes(uri);
// if toBase specifies a protocol path, ensure this is the same protocol as fromBase, if not
// use absolute path at fromBase
var toBaseProtocol = toBase.match(protocolRegEx);
var fromBaseProtocol = fromBase.match(protocolRegEx);
if (fromBaseProtocol && (!toBaseProtocol || toBaseProtocol[1] != fromBaseProtocol[1] || toBaseProtocol[2] != fromBaseProtocol[2]))
return absoluteURI(uri, fromBase);
else {
return relativeURI(absoluteURI(uri, fromBase), toBase);
}
};
// given a relative URI, calculate the absolute URI
function absoluteURI(uri, base) {
if (uri.substr(0, 2) == './')
uri = uri.substr(2);
// absolute urls are left in tact
if (uri.match(absUrlRegEx) || uri.match(protocolRegEx))
return uri;
var baseParts = base.split('/');
var uriParts = uri.split('/');
baseParts.pop();
while (curPart = uriParts.shift())
if (curPart == '..')
baseParts.pop();
else
baseParts.push(curPart);
return baseParts.join('/');
};
// given an absolute URI, calculate the relative URI
function relativeURI(uri, base) {
// reduce base and uri strings to just their difference string
var baseParts = base.split('/');
baseParts.pop();
base = baseParts.join('/') + '/';
i = 0;
while (base.substr(i, 1) == uri.substr(i, 1))
i++;
while (base.substr(i, 1) != '/')
i--;
base = base.substr(i + 1);
uri = uri.substr(i + 1);
// each base folder difference is thus a backtrack
baseParts = base.split('/');
var uriParts = uri.split('/');
out = '';
while (baseParts.shift())
out += '../';
// finally add uri parts
while (curPart = uriParts.shift())
out += curPart + '/';
return out.substr(0, out.length - 1);
};
var normalizeCSS = function(source, fromBase, toBase) {
fromBase = removeDoubleSlashes(fromBase);
toBase = removeDoubleSlashes(toBase);
var urlRegEx = /@import\s*("([^"]*)"|'([^']*)')|url\s*\((?!#)\s*(\s*"([^"]*)"|'([^']*)'|[^\)]*\s*)\s*\)/ig;
var result, url, source;
while (result = urlRegEx.exec(source)) {
url = result[3] || result[2] || result[5] || result[6] || result[4];
var newUrl;
newUrl = convertURIBase(url, fromBase, toBase);
var quoteLen = result[5] || result[6] ? 1 : 0;
source = source.substr(0, urlRegEx.lastIndex - url.length - quoteLen - 1) + newUrl + source.substr(urlRegEx.lastIndex - quoteLen - 1);
urlRegEx.lastIndex = urlRegEx.lastIndex + (newUrl.length - url.length);
}
return source;
};
normalizeCSS.convertURIBase = convertURIBase;
normalizeCSS.absoluteURI = absoluteURI;
normalizeCSS.relativeURI = relativeURI;
return normalizeCSS;
});
//>>excludeEnd('excludeRequireCss')

View File

@@ -0,0 +1,10 @@
{
"name": "require-css",
"version": "0.1.10",
"volo": {
"type": "directory"
},
"scripts": {
"test": "node test/test.js"
}
}