@@ -6,16 +6,51 @@ var FileSystemLoader = require('css-modules-loader-core/lib/file-system-loader')
66var assign = require ( 'object-assign' ) ;
77var stringHash = require ( 'string-hash' ) ;
88
9+
10+ /*
11+ Custom `generateScopedName` function for `postcss-modules-scope`.
12+ Short names consisting of source hash and line number.
13+ */
14+ function generateShortName ( name , filename , css ) {
15+ // first occurrence of the name
16+ // TOOD: better match with regex
17+ var i = css . indexOf ( '.' + name ) ;
18+ var numLines = css . substr ( 0 , i ) . split ( / [ \r \n ] / ) . length ;
19+
20+ var hash = stringHash ( css ) . toString ( 36 ) . substr ( 0 , 5 ) ;
21+ return '_' + name + '_' + hash + '_' + numLines ;
22+ }
23+
924/*
1025 Custom `generateScopedName` function for `postcss-modules-scope`.
1126 Appends a hash of the css source.
1227*/
13- function createScopedNameFunc ( plugin ) {
14- var orig = plugin . generateScopedName ;
15- return function ( name , filename , css ) {
16- var hash = stringHash ( css ) . toString ( 36 ) . substr ( 0 , 5 ) ;
17- return orig . apply ( plugin , arguments ) + '___' + hash ;
18- } ;
28+ function generateLongName ( name , filename , css ) {
29+ var sanitisedPath = filename . replace ( / \. [ ^ \. \/ \\ ] + $ / , '' )
30+ . replace ( / [ \W _ ] + / g, '_' )
31+ . replace ( / ^ _ | _ $ / g, '' ) ;
32+
33+ var hash = stringHash ( css ) . toString ( 36 ) . substr ( 0 , 5 ) ;
34+ return '_' + sanitisedPath + '__' + name + '___' + hash ;
35+ }
36+
37+ /*
38+ Get the default plugins and apply options.
39+ */
40+ function getDefaultPlugins ( options ) {
41+ var scope = Core . scope ;
42+ var customNameFunc = options . generateScopedName ;
43+ var defaultNameFunc = process . env . NODE_ENV === 'production' ?
44+ generateShortName :
45+ generateLongName ;
46+
47+ scope . generateScopedName = customNameFunc || defaultNameFunc ;
48+
49+ return [
50+ Core . localByDefault
51+ , Core . extractImports
52+ , scope
53+ ] ;
1954}
2055
2156/*
@@ -71,7 +106,7 @@ module.exports = function (browserify, options) {
71106 // PostCSS plugins passed to FileSystemLoader
72107 var plugins = options . use || options . u ;
73108 if ( ! plugins ) {
74- plugins = Core . defaultPlugins ;
109+ plugins = getDefaultPlugins ( options ) ;
75110 }
76111 else {
77112 if ( typeof plugins === 'string' ) {
@@ -95,7 +130,7 @@ module.exports = function (browserify, options) {
95130 if ( name === 'postcss-modules-scope' ) {
96131 options [ name ] = options [ name ] || { } ;
97132 if ( ! options [ name ] . generateScopedName ) {
98- options [ name ] . generateScopedName = createScopedNameFunc ( plugin ) ;
133+ options [ name ] . generateScopedName = generateLongName ;
99134 }
100135 }
101136
@@ -174,3 +209,6 @@ module.exports = function (browserify, options) {
174209
175210 return browserify ;
176211} ;
212+
213+ module . exports . generateShortName = generateShortName ;
214+ module . exports . generateLongName = generateLongName ;
0 commit comments