quasar

Форк
0
/
build.utils.js 
173 строки · 4.0 Кб
1
const path = require('node:path')
2
const fse = require('fs-extra')
3
const zlib = require('zlib')
4
const { green, blue, red, magenta, grey, underline } = require('chalk')
5

6
const kebabRegex = /[A-Z\u00C0-\u00D6\u00D8-\u00DE]/g
7
const tableData = []
8

9
const { version } = require('../package.json')
10

11
process.on('exit', code => {
12
  if (code === 0 && tableData.length > 0) {
13
    const { table } = require('table')
14

15
    tableData.sort((a, b) => {
16
      return a[ 0 ] === b[ 0 ]
17
        ? a[ 1 ] < b[ 1 ] ? -1 : 1
18
        : a[ 0 ] < b[ 0 ] ? -1 : 1
19
    })
20

21
    tableData.unshift([
22
      underline('Ext'),
23
      underline('Filename'),
24
      underline('Size'),
25
      underline('Gzipped')
26
    ])
27

28
    const output = table(tableData, {
29
      columns: {
30
        0: { alignment: 'right' },
31
        1: { alignment: 'left' },
32
        2: { alignment: 'right' },
33
        3: { alignment: 'right' }
34
      }
35
    })
36

37
    console.log()
38
    console.log(` Summary of Quasar v${ version }:`)
39
    console.log(output)
40
  }
41
})
42

43
function getSize (code) {
44
  return (code.length / 1024).toFixed(2) + 'kb'
45
}
46

47
module.exports.createFolder = function (folder) {
48
  const dir = path.join(__dirname, '..', folder)
49
  fse.ensureDirSync(dir)
50
}
51

52
function getDestinationInfo (dest) {
53
  if (dest.endsWith('.json')) {
54
    return {
55
      banner: grey('[json]'),
56
      tableEntryType: grey('json'),
57
      toTable: false
58
    }
59
  }
60

61
  if (dest.endsWith('.js') || dest.endsWith('.mjs')) {
62
    return {
63
      banner: green('[js]  '),
64
      tableEntryType: green('js'),
65
      toTable: dest.indexOf('dist/quasar') > -1
66
    }
67
  }
68

69
  if (dest.endsWith('.css') || dest.endsWith('.styl') || dest.endsWith('.sass')) {
70
    return {
71
      banner: blue('[css] '),
72
      tableEntryType: blue('css'),
73
      toTable: true
74
    }
75
  }
76

77
  if (dest.endsWith('.ts')) {
78
    return {
79
      banner: magenta('[ts]  '),
80
      tableEntryType: magenta('ts'),
81
      toTable: false
82
    }
83
  }
84

85
  logError(`Unknown file type using buildUtils.writeFile: ${ dest }`)
86
  process.exit(1)
87
}
88

89
module.exports.writeFile = function (dest, code, zip) {
90
  const { banner, tableEntryType, toTable } = getDestinationInfo(dest)
91

92
  const fileSize = getSize(code)
93
  const filePath = path.relative(process.cwd(), dest)
94

95
  return new Promise((resolve, reject) => {
96
    function report (gzippedString, gzippedSize) {
97
      console.log(`${ banner } ${ filePath.padEnd(49) } ${ fileSize.padStart(8) }${ gzippedString || '' }`)
98

99
      if (toTable) {
100
        tableData.push([
101
          tableEntryType,
102
          filePath,
103
          fileSize,
104
          gzippedSize || '-'
105
        ])
106
      }
107

108
      resolve(code)
109
    }
110

111
    fse.writeFile(dest, code, err => {
112
      if (err) return reject(err)
113
      if (zip) {
114
        zlib.gzip(code, (err, zipped) => {
115
          if (err) return reject(err)
116
          const size = getSize(zipped)
117
          report(` (gzipped: ${ size.padStart(8) })`, size)
118
        })
119
      }
120
      else {
121
        report()
122
      }
123
    })
124
  })
125
}
126

127
module.exports.readFile = function (file) {
128
  return fse.readFileSync(file, 'utf-8')
129
}
130

131
module.exports.writeFileIfChanged = function (dest, newContent, zip) {
132
  let currentContent = ''
133
  try {
134
    currentContent = fse.readFileSync(dest, 'utf-8')
135
  }
136
  catch (e) {}
137

138
  return newContent.split(/[\n\r]+/).join('\n') !== currentContent.split(/[\n\r]+/).join('\n')
139
    ? module.exports.writeFile(dest, newContent, zip)
140
    : Promise.resolve()
141
}
142

143
module.exports.convertToCjs = function (content, banner = '') {
144
  return banner + content
145
    .replace(/export default {/, 'module.exports = {')
146
    .replace(/import {/g, 'const {')
147
    .replace(/} from '(.*)'/g, (_, pkg) => `} = require('${ pkg }')`)
148
}
149

150
function logError (err) {
151
  console.error('\n' + red('[Error]'), err)
152
  console.log()
153
}
154

155
module.exports.logError = logError
156

157
module.exports.kebabCase = function (str) {
158
  return str.replace(
159
    kebabRegex,
160
    match => '-' + match.toLowerCase()
161
  ).substring(1)
162
}
163

164
module.exports.clone = function clone (data) {
165
  const str = JSON.stringify(data)
166

167
  if (str) {
168
    return JSON.parse(str)
169
  }
170
}
171

172
const testFileRE = /test/
173
module.exports.filterTestFiles = file => testFileRE.test(file) === false
174

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.