Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

gulpfile.js 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405
  1. /**
  2. @author : Caven Chen
  3. **/
  4. 'use strict'
  5. import fse from 'fs-extra'
  6. import path from 'path'
  7. import gulp from 'gulp'
  8. import esbuild from 'esbuild'
  9. import concat from 'gulp-concat'
  10. import { rollup } from 'rollup'
  11. import clean from 'gulp-clean'
  12. import commonjs from '@rollup/plugin-commonjs'
  13. import resolve from '@rollup/plugin-node-resolve'
  14. import terser from '@rollup/plugin-terser'
  15. import scss from 'rollup-plugin-scss'
  16. import javascriptObfuscator from 'gulp-javascript-obfuscator'
  17. import { babel } from '@rollup/plugin-babel'
  18. import startServer from './server.js'
  19. import inlineImage from 'esbuild-plugin-inline-image'
  20. import { glsl } from 'esbuild-plugin-glsl'
  21. import chokidar from 'chokidar'
  22. import shell from 'shelljs'
  23. import chalk from 'chalk'
  24. const obfuscatorConfig = {
  25. compact: true, //压缩代码
  26. identifierNamesGenerator: 'hexadecimal', //标识符的混淆方式 hexadecimal(十六进制) mangled(短标识符)
  27. renameGlobals: false, //是否启用全局变量和函数名称的混淆
  28. rotateStringArray: true, //通过固定和随机(在代码混淆时生成)的位置移动数组。这使得将删除的字符串的顺序与其原始位置相匹配变得更加困难。如果原始源代码不小,建议使用此选项,因为辅助函数可以引起注意。
  29. selfDefending: true, //混淆后的代码,不能使用代码美化,同时需要配置 compact:true;
  30. stringArray: true, //删除字符串文字并将它们放在一个特殊的数组中
  31. stringArrayEncoding: ['base64'],
  32. stringArrayThreshold: 0.75,
  33. transformObjectKeys: false,
  34. unicodeEscapeSequence: false, //允许启用/禁用字符串转换为unicode转义序列。Unicode转义序列大大增加了代码大小,并且可以轻松地将字符串恢复为原始视图。建议仅对小型源代码启用此选项。
  35. }
  36. const buildConfig = {
  37. entryPoints: ['src/DC.js'],
  38. bundle: true,
  39. color: true,
  40. legalComments: `inline`,
  41. logLimit: 0,
  42. target: `es2019`,
  43. minify: false,
  44. sourcemap: false,
  45. write: true,
  46. logLevel: 'info',
  47. external: [`http`, `https`, `url`, `zlib`],
  48. plugins: [
  49. inlineImage({
  50. limit: -1,
  51. }),
  52. glsl(),
  53. ],
  54. }
  55. const packageJson = fse.readJsonSync('./package.json')
  56. const plugins = [
  57. resolve({ preferBuiltins: true }),
  58. commonjs(),
  59. babel({
  60. babelHelpers: 'runtime',
  61. presets: [
  62. [
  63. '@babel/preset-env',
  64. {
  65. modules: false,
  66. targets: {
  67. browsers: ['> 1%', 'last 2 versions', 'ie >= 10'],
  68. },
  69. },
  70. ],
  71. ],
  72. plugins: ['@babel/plugin-transform-runtime'],
  73. }),
  74. ]
  75. function getTime() {
  76. let now = new Date()
  77. let m = now.getMonth() + 1
  78. m = m < 10 ? '0' + m : m
  79. let d = now.getDate()
  80. d = d < 10 ? '0' + d : d
  81. return `${now.getFullYear()}-${m}-${d}`
  82. }
  83. async function buildNamespace(options) {
  84. const bundle = await rollup({
  85. input: 'libs/index.js',
  86. plugins: [...plugins, ...[options.dev ? null : terser()]],
  87. onwarn: (message) => {
  88. // Ignore eval warnings in third-party code we don't have control over
  89. if (message.code === 'EVAL' && /protobufjs/.test(message.loc.file)) {
  90. return
  91. }
  92. if (message.code === 'CIRCULAR_DEPENDENCY') {
  93. return
  94. }
  95. console.log(message)
  96. },
  97. })
  98. return bundle.write({
  99. name: 'DC.__namespace',
  100. file: options.node ? 'dist/namespace.cjs' : 'dist/namespace.js',
  101. format: options.node ? 'cjs' : 'umd',
  102. sourcemap: false,
  103. banner: options.node ? '(function(){' : '',
  104. footer: options.node ? '})()' : '',
  105. })
  106. }
  107. async function buildCSS() {
  108. const bundle = await rollup({
  109. input: 'src/themes/index.js',
  110. plugins: [
  111. commonjs(),
  112. resolve({ preferBuiltins: true }),
  113. scss({
  114. outputStyle: 'compressed',
  115. fileName: 'dc.min.css',
  116. }),
  117. ],
  118. })
  119. return bundle.write({
  120. file: 'dist/dc.min.css',
  121. })
  122. }
  123. async function buildModules(options) {
  124. const dcPath = path.join('src', 'DC.js')
  125. const content = await fse.readFile(path.join('src', 'index.js'), 'utf8')
  126. await fse.ensureFile(dcPath)
  127. const exportVersion = `export const VERSION = '${packageJson.version}'`
  128. const cmdOut_content = await fse.readFile(
  129. path.join('src', 'copyright', 'cmdOut.js'),
  130. 'utf8'
  131. )
  132. const exportCmdOut = `
  133. export function __cmdOut() {
  134. ${cmdOut_content
  135. .replace('{{__VERSION__}}', packageJson.version)
  136. .replace('{{__TIME__}}', getTime())
  137. .replace(
  138. '{{__ENGINE_VERSION__}}',
  139. packageJson.devDependencies['@cesium/engine'].replace('^', '')
  140. )
  141. .replace('{{__AUTHOR__}}', packageJson.author)
  142. .replace('{{__HOME_PAGE__}}', packageJson.homepage)
  143. .replace('{{__REPOSITORY__}}', packageJson.repository)}
  144. }`
  145. const exportNamespace = `
  146. export const __namespace = {
  147. Cesium: exports.Cesium,
  148. Supercluster: exports.Supercluster,
  149. CryptoJS: exports.CryptoJS
  150. }
  151. `
  152. // Build IIFE
  153. if (options.iife) {
  154. await fse.outputFile(
  155. dcPath,
  156. `
  157. ${exportVersion}
  158. ${exportCmdOut}
  159. ${content}
  160. `,
  161. {
  162. encoding: 'utf8',
  163. }
  164. )
  165. await esbuild.build({
  166. ...buildConfig,
  167. format: 'iife',
  168. globalName: 'DC',
  169. outfile: path.join('dist', 'modules.js'),
  170. })
  171. }
  172. // Build Node、
  173. if (options.node) {
  174. await fse.outputFile(
  175. dcPath,
  176. `
  177. ${exportNamespace}
  178. ${exportVersion}
  179. ${exportCmdOut}
  180. ${content}
  181. `,
  182. {
  183. encoding: 'utf8',
  184. }
  185. )
  186. await esbuild.build({
  187. ...buildConfig,
  188. format: 'cjs',
  189. platform: 'node',
  190. define: {
  191. TransformStream: 'null',
  192. },
  193. outfile: path.join('dist', 'modules.cjs'),
  194. })
  195. }
  196. // remove DC.js
  197. await fse.remove(dcPath)
  198. }
  199. async function combineJs(options) {
  200. // combine for iife
  201. if (options.iife) {
  202. if (options.obfuscate) {
  203. await gulp
  204. .src('dist/modules.js')
  205. .pipe(javascriptObfuscator(obfuscatorConfig))
  206. .pipe(gulp.src('dist/namespace.js'))
  207. .pipe(concat('dc.min.js'))
  208. .pipe(gulp.dest('dist'))
  209. .on('end', () => {
  210. addCopyright(options)
  211. deleteTempFile(options)
  212. })
  213. } else {
  214. await gulp
  215. .src(['dist/modules.js', 'dist/namespace.js'])
  216. .pipe(concat('dc.min.js'))
  217. .pipe(gulp.dest('dist'))
  218. .on('end', () => {
  219. addCopyright(options)
  220. deleteTempFile(options)
  221. })
  222. }
  223. }
  224. // combine for node
  225. if (options.node) {
  226. if (options.obfuscate) {
  227. await gulp
  228. .src('dist/modules.cjs')
  229. .pipe(javascriptObfuscator(obfuscatorConfig))
  230. .pipe(gulp.dest('dist'))
  231. .on('end', async () => {
  232. await gulp
  233. .src(['dist/namespace.cjs', 'dist/modules.cjs'])
  234. .pipe(concat('index.cjs'))
  235. .pipe(gulp.dest('dist'))
  236. .on('end', () => {
  237. addCopyright(options)
  238. deleteTempFile(options)
  239. })
  240. })
  241. } else {
  242. await gulp
  243. .src(['dist/namespace.cjs', 'dist/modules.cjs'])
  244. .pipe(concat('index.cjs'))
  245. .pipe(gulp.dest('dist'))
  246. .on('end', () => {
  247. addCopyright(options)
  248. deleteTempFile(options)
  249. })
  250. }
  251. }
  252. }
  253. async function copyAssets() {
  254. await fse.emptyDir('dist/resources')
  255. await gulp
  256. .src('./node_modules/@cesium/engine/Build/Workers/**', { nodir: true })
  257. .pipe(gulp.dest('dist/resources/Workers'))
  258. await gulp
  259. .src('./node_modules/@cesium/engine/Source/Assets/**', { nodir: true })
  260. .pipe(gulp.dest('dist/resources/Assets'))
  261. await gulp
  262. .src('./node_modules/@cesium/engine/Source/ThirdParty/**', { nodir: true })
  263. .pipe(gulp.dest('dist/resources/ThirdParty'))
  264. }
  265. async function addCopyright(options) {
  266. let header = await fse.readFile(
  267. path.join('src', 'copyright', 'header.js'),
  268. 'utf8'
  269. )
  270. header = header
  271. .replace('{{__VERSION__}}', packageJson.version)
  272. .replace('{{__AUTHOR__}}', packageJson.author)
  273. .replace('{{__REPOSITORY__}}', packageJson.repository)
  274. if (options.iife) {
  275. let filePath = path.join('dist', 'dc.min.js')
  276. const content = await fse.readFile(filePath, 'utf8')
  277. await fse.outputFile(filePath, `${header}${content}`, { encoding: 'utf8' })
  278. }
  279. if (options.node) {
  280. let filePath = path.join('dist', 'index.cjs')
  281. const content = await fse.readFile(filePath, 'utf8')
  282. await fse.outputFile(filePath, `${header}${content}`, { encoding: 'utf8' })
  283. }
  284. }
  285. async function deleteTempFile(options) {
  286. if (options.iife) {
  287. await gulp
  288. .src(['dist/namespace.js', 'dist/modules.js'], { read: false })
  289. .pipe(clean())
  290. }
  291. if (options.node) {
  292. await gulp
  293. .src(['dist/namespace.cjs', 'dist/modules.cjs'], { read: false })
  294. .pipe(clean())
  295. }
  296. }
  297. async function regenerate(option, content) {
  298. await fse.remove('dist/dc.min.js')
  299. await fse.remove('dist/dc.min.css')
  300. await fse.outputFile(path.join('dist', 'namespace.js'), content)
  301. await buildModules(option)
  302. await combineJs(option)
  303. await buildCSS()
  304. }
  305. export const build = gulp.series(
  306. () => buildNamespace({ node: true }),
  307. () => buildModules({ node: true }),
  308. () => combineJs({ node: true }),
  309. () => buildNamespace({ iife: true }),
  310. () => buildModules({ iife: true }),
  311. () => combineJs({ iife: true }),
  312. buildCSS,
  313. copyAssets
  314. )
  315. export const buildNode = gulp.series(
  316. () => buildNamespace({ node: true }),
  317. () => buildModules({ node: true }),
  318. () => combineJs({ node: true }),
  319. buildCSS,
  320. copyAssets
  321. )
  322. export const buildIIFE = gulp.series(
  323. () => buildNamespace({ iife: true }),
  324. () => buildModules({ iife: true }),
  325. () => combineJs({ iife: true }),
  326. buildCSS,
  327. copyAssets
  328. )
  329. export const buildRelease = gulp.series(
  330. () => buildNamespace({ node: true }),
  331. () => buildModules({ node: true }),
  332. () => combineJs({ node: true, obfuscate: true }),
  333. () => buildNamespace({ iife: true }),
  334. () => buildModules({ iife: true }),
  335. () => combineJs({ iife: true, obfuscate: true }),
  336. buildCSS,
  337. copyAssets
  338. )
  339. export const dev = gulp.series(
  340. () => buildNamespace({ dev: true }),
  341. copyAssets,
  342. () => {
  343. shell.echo(chalk.yellow('============= start dev =============='))
  344. const watcher = chokidar.watch('src', {
  345. persistent: true,
  346. awaitWriteFinish: {
  347. stabilityThreshold: 1000,
  348. pollInterval: 100,
  349. },
  350. })
  351. fse.readFile(path.join('dist', 'namespace.js'), 'utf8').then((content) => {
  352. watcher
  353. .on('ready', async () => {
  354. await regenerate({ iife: true }, content)
  355. await startServer()
  356. })
  357. .on('change', async () => {
  358. let now = new Date()
  359. await regenerate({ iife: true }, content)
  360. shell.echo(
  361. chalk.green(
  362. `regenerate lib takes ${new Date().getTime() - now.getTime()} ms`
  363. )
  364. )
  365. })
  366. })
  367. return watcher
  368. }
  369. )
  370. export const server = gulp.series(startServer)