33var fs = require ( 'fs' )
44var path = require ( 'path' )
55var mkdirp = require ( 'mkdirp' )
6+ var mime = require ( 'mime' )
67
78var defaultOptions = {
89 img : 'src' ,
9- image : 'xlink:href'
10+ image : 'xlink:href' ,
11+ limit : 10 * 1024
1012}
1113
1214module . exports = ( userOptions , fileOptions ) => {
@@ -26,32 +28,43 @@ function transform (node, options, fileOptions) {
2628 if ( node . tag === tag && node . attrs ) {
2729 var attributes = options [ tag ]
2830 if ( typeof attributes === 'string' ) {
29- node . attrs . some ( attr => rewrite ( attr , node . attrsMap , attributes , fileOptions ) )
31+ rewrite ( node . attrsMap , attributes , fileOptions , options . limit )
3032 } else if ( Array . isArray ( attributes ) ) {
31- attributes . forEach ( item => node . attrs . some ( attr => rewrite ( attr , node . attrsMap , item , fileOptions ) ) )
33+ attributes . forEach ( item => rewrite ( node . attrsMap , item , fileOptions , options . limit ) )
3234 }
3335 }
3436 }
3537}
3638
37- function rewrite ( attr , attrsMap , name , fileOptions ) {
38- if ( attr . name === name ) {
39- var value = attr . value
40- var isStatic = value . charAt ( 0 ) === '"' && value . charAt ( value . length - 1 ) === '"'
41- if ( ! isStatic ) {
42- return
43- }
44- var firstChar = value . charAt ( 1 )
39+ function rewrite ( attrsMap , name , fileOptions , limit ) {
40+ var value = attrsMap [ name ]
41+ if ( value ) {
42+ var firstChar = value . charAt ( 0 )
4543 if ( firstChar === '.' ) {
4644 // 资源路径
47- var assetPath = path . join ( path . dirname ( fileOptions . resourcePath ) , value . slice ( 1 , - 1 ) )
48- // 重写路径,为了避免重名,在webpack输出目录下新建copy-asset目录,资源保存到这里
49- var assetOutputPath = path . join ( 'copy-asset' , path . relative ( process . cwd ( ) , assetPath ) . replace ( / ^ s r c / , '' ) )
50- attrsMap [ name ] = `/${ assetOutputPath } `
51- // 拷贝资源
52- copyAsset ( assetPath , path . resolve ( fileOptions . outputPath , assetOutputPath ) )
45+ var assetPath = path . join ( path . dirname ( fileOptions . resourcePath ) , value )
46+ // 小于limit的资源转base64
47+ var str = assetToBase64 ( assetPath , limit )
48+ if ( str ) {
49+ attrsMap [ name ] = `data:${ mime . getType ( assetPath ) || '' } ;base64,${ str } `
50+ } else {
51+ // 重写路径,为了避免重名,在webpack输出目录下新建copy-asset目录,资源保存到这里
52+ var assetOutputPath = path . join ( 'copy-asset' , path . relative ( process . cwd ( ) , assetPath ) . replace ( / ^ s r c / , '' ) )
53+ attrsMap [ name ] = `/${ assetOutputPath } `
54+ copyAsset ( assetPath , path . resolve ( fileOptions . outputPath , assetOutputPath ) )
55+ }
56+ }
57+ }
58+ }
59+
60+ function assetToBase64 ( assetPath , limit ) {
61+ try {
62+ var buffer = fs . readFileSync ( assetPath )
63+ if ( buffer . length <= limit ) {
64+ return buffer . toString ( 'base64' )
5365 }
54- return true
66+ } catch ( err ) {
67+ console . error ( 'ReadFile Error:' + err )
5568 }
5669}
5770
0 commit comments