diff --git a/gulp/browserify_prelude.js b/gulp/browserify_prelude.js deleted file mode 100644 index f31f153b1b..0000000000 --- a/gulp/browserify_prelude.js +++ /dev/null @@ -1,33 +0,0 @@ - -// Based on https://github.com/substack/browser-pack/blob/master/prelude.js - -// modules are defined as an array -// [ module function, map of requireuires ] -// -// map of requireuires is short require name -> numeric require -// -// anything defined in a previous bundle is accessed via the -// orig method which is the requireuire for previous bundles - -(function outer (modules, cache, entry) { - function newRequire(name, jumped){ - var module = cache[name]; - if(!module) { - var moduleData = modules[name]; - if(!moduleData) { - // this module is excluded from engine - return undefined; - } - var exports = {}; - module = cache[name] = {exports: exports}; - moduleData[0](function(x){ - return newRequire(moduleData[1][x] || x); - },module,exports); - } - return module.exports; - } - for(var i=0;i= 6.16.0 - // parserOpts: { - // allowReturnOutsideFunction: true, - // }, - - ast: false, - babelrc: false, - highlightCode: false, - sourceMaps: true, - compact: false - }) - .transform(aliasify, (options && options.aliasifyConfig) || {}); -}; diff --git a/gulp/util/fix-jsb-javascriptcore.js b/gulp/util/fix-jsb-javascriptcore.js deleted file mode 100644 index c6cde82bd0..0000000000 --- a/gulp/util/fix-jsb-javascriptcore.js +++ /dev/null @@ -1,40 +0,0 @@ - -// fix `typeof constructor` on JavaScriptCore - -const ES = require('event-stream'); -const Path = require('path'); - -const getRealTypeOfObj = (function __realTypeOfObj (obj) { - if (obj) { - if (obj.toString) { - if (obj.toString() === '[object CallbackConstructor]') - return 'function'; - } - else { - // "Cannot convert object to primitive value" - } - } - return 'object'; -}).toString(); - -const TYPEOF_SHIM = `\n${getRealTypeOfObj}\nvar __typeofVal = "";`; - -const TYPEOF_REG = /typeof\s+([$A-Za-z_][0-9A-Za-z_$\.\[\]]*)([\s!=;\)])/g; -const TYPEOF_REPLACEMENT = '(__typeofVal = typeof $1, __typeofVal === "object" ? __realTypeOfObj($1) : __typeofVal)$2'; - -module.exports = function () { - return ES.through(function (file) { - if (Path.extname(file.path) === '.js') { - var content = file.contents.toString(); - - content = content.replace(TYPEOF_REG, TYPEOF_REPLACEMENT); - content += TYPEOF_SHIM; - - // make shim as local variables so that variable names will be mangled - content = '(function () {' + content + '})();'; - - file.contents = new Buffer(content); - } - this.emit('data', file); - }); -}; diff --git a/gulp/util/handleErrors.js b/gulp/util/handleErrors.js deleted file mode 100644 index 62531aab57..0000000000 --- a/gulp/util/handleErrors.js +++ /dev/null @@ -1,52 +0,0 @@ -/**************************************************************************** - Copyright (c) 2013-2016 Chukong Technologies Inc. - - http://www.cocos.com - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated engine source code (the "Software"), a limited, - worldwide, royalty-free, non-assignable, revocable and non-exclusive license - to use Cocos Creator solely to develop games on your target platforms. You shall - not use Cocos Creator software for developing other software or tools that's - used for developing games. You are not granted to publish, distribute, - sublicense, and/or sell copies of Cocos Creator. - - The software or tools in this License Agreement are licensed, not sold. - Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. - - 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. - ****************************************************************************/ - -// https://github.com/GoodBoyDigital/pixi.js/blob/c984191777001580b3a81f41cfe354b58d99757f/gulp/util/handleErrors.js -var gutil = require('gulp-util'), - plumber = require('gulp-plumber'), - ERROR = gutil.colors.red('[ERROR]'); - -function errorHandler(err) { - var msg = err.toString(); - - if (msg === '[object Object]') { - msg = err; - } - - gutil.log(ERROR, err); - - if (err.stack) { - gutil.log(ERROR, err.stack); - } - - // Keep gulp from hanging on this task - this.emit('end'); -} - -module.exports = function () { - return plumber(errorHandler); -}; - -module.exports.handler = errorHandler; diff --git a/gulp/util/utils.js b/gulp/util/utils.js deleted file mode 100644 index a23e8dd84b..0000000000 --- a/gulp/util/utils.js +++ /dev/null @@ -1,145 +0,0 @@ - -const PLATFORM_MACROS = ['CC_EDITOR', 'CC_PREVIEW', 'CC_BUILD', 'CC_TEST']; -const FLAGS = ['jsb', 'runtime', 'wechatgame', 'wechatgameSub', 'qqplay', 'debug', 'nativeRenderer']; - -// generate macros for uglify's global_defs -// available platforms: 'editor' | 'preview' | 'build' | 'test' -// available keys of flags: 'jsb' | 'runtime' | 'wechatgame' | 'qqplay' | 'debug' | 'nativeRenderer' -exports.getMacros = function (platform, flags) { - // platform macros - var platformMacro = 'CC_' + platform.toUpperCase(); - if (PLATFORM_MACROS.indexOf(platformMacro) === -1) { - throw new Error('Unknown platform: ' + platform); - } - var res = {}; - for (let i = 0; i < PLATFORM_MACROS.length; i++) { - let macro = PLATFORM_MACROS[i]; - res[macro] = (macro === platformMacro); - } - - // flag macros - if (flags) { - for (let flag in flags) { - if (flags.hasOwnProperty(flag) && flags[flag]) { - if (FLAGS.indexOf(flag) === -1) { - throw new Error('Unknown flag: ' + flag); - } - } - } - } - for (let i = 0; i < FLAGS.length; i++) { - let flag = FLAGS[i]; - let macro = 'CC_' + flag.toUpperCase(); - res[macro] = !!(flags && flags[flag]); - } - - // debug macros - res['CC_DEV'] = res['CC_EDITOR'] || res['CC_PREVIEW'] || res['CC_TEST']; - res['CC_DEBUG'] = res['CC_DEBUG'] || res['CC_DEV']; - res['CC_SUPPORT_JIT'] = !(res['CC_WECHAT'] || res['CC_RUNTIME_BASED']); - return res; -}; - -// see https://github.com/mishoo/UglifyJS2/tree/harmony#compress-options -exports.getUglifyOptions = function (platform, flags) { - var global_defs = exports.getMacros(platform, flags); - var releaseMode = !global_defs['CC_DEBUG']; - - var optimizeForJSC = releaseMode && global_defs['CC_JSB']; - if (optimizeForJSC) { - return { - parse: { - bare_returns: true - }, - toplevel: false, - compress: { - global_defs: global_defs, - negate_iife: false, - sequences: false, - keep_infinity: true, // reduce jsc file size - typeofs: false, - inline: 1, // workaround mishoo/UglifyJS2#2842 - }, - output: { - beautify: true, // really preserve_lines - indent_level: 0, // reduce jsc file size - } - }; - } - - if (releaseMode) { - return { - parse: { - bare_returns: true - }, - toplevel: false, - compress: { - global_defs: global_defs, - negate_iife: false, - inline: 1, // workaround mishoo/UglifyJS2#2842 - }, - output: { - ascii_only: true, - } - }; - } - else { - return { - parse: { - bare_returns: true - }, - toplevel: false, - compress: { - global_defs: global_defs, - negate_iife: false, - sequences: false, // join consecutive statements with the “comma operator” - properties: false, // optimize property access: a["foo"] → a.foo - // dead_code: true, // discard unreachable code - drop_debugger: false, // discard “debugger” statements - // ecma: 5, // transform ES5 code into smaller ES6+ equivalent forms - // evaluate: true, // evaluate constant expressions - unsafe: false, // some unsafe optimizations (see below) - // computed_props: true, - // conditionals: false, // optimize if-s and conditional expressions - comparisons: false, // optimize comparisons - booleans: false, // optimize boolean expressions - typeofs: false, // Transforms typeof foo == "undefined" into foo === void 0. Note: recommend to set this value to false for IE10 and earlier versions due to known issues. - loops: false, // optimize loops - unused: false, // drop unused variables/functions - hoist_funs: false, // hoist function declarations - hoist_props: false, - hoist_vars: false, // hoist variable declarations - if_return: false, // optimize if-s followed by return/continue - inline: false, // embed simple functions - join_vars: false, // join var declarations - collapse_vars: false, // Collapse single-use non-constant variables - side effects permitting. - reduce_funcs: false, - reduce_vars: false, // Improve optimization on variables assigned with and used as constant values. - //warnings: true, - pure_getters: false, - pure_funcs: null, - drop_console: false, - // expression: false, // Pass true to preserve completion values from terminal statements without return, e.g. in bookmarklets. - keep_fargs: true, - keep_fnames: true, - keep_infinity: true, // Pass true to prevent Infinity from being compressed into 1/0, which may cause performance issues on Chrome. - side_effects: false, // drop side-effect-free statements - }, - mangle: false, - //preserveComments: 'all', - output: { - // http://lisperator.net/uglifyjs/codegen - beautify: true, - indent_level: 2, - ascii_only: true, - }, - }; - } -}; - -exports.uglify = function (platform, isJSB, isDebugBuild) { - const Composer = require('gulp-uglify/composer'); - const Uglify = require('uglify-es'); - const minify = Composer(Uglify); - return minify(exports.getUglifyOptions(platform, isJSB, isDebugBuild)); -}; diff --git a/gulpfile.js b/gulpfile.js index 30191a14cd..a5efa460c5 100644 --- a/gulpfile.js +++ b/gulpfile.js @@ -24,186 +24,62 @@ THE SOFTWARE. */ +/* eslint-disable @typescript-eslint/no-require-imports */ +/* eslint-disable @typescript-eslint/no-var-requires */ + 'use strict'; -const Path = require('path'); const gulp = require('gulp'); -const Del = require('del'); -const Shell = require('gulp-shell'); +const fs = require('fs-extra'); +const ps = require('path'); +const cp = require('child_process'); -const Engine = require('./gulp/tasks/engine'); -const Test = require('./gulp/tasks/test'); -const Watch = require('./gulp/tasks/watch'); -const APIBuilder = require('./gulp/util/api-docs-build'); - -///////////// -// engine // -///////////// - -gulp.task('build-debug-infos', function () { - Engine.buildDebugInfos(); +gulp.task('build-debug-infos', async () => { + return await Promise.resolve(require('./gulp/tasks/buildDebugInfos')()); }); -gulp.task('build-html5-dev', ['clean-cache', 'build-debug-infos'], function (done) { - Engine.buildCocosJs('./index.js', './bin/cocos2d-js.js', [], done); -}); - -gulp.task('build-html5-min', ['clean-cache', 'build-debug-infos'], function (done) { - Engine.buildCocosJsMin('./index.js', './bin/cocos2d-js-min.js', [], done); -}); - -gulp.task('build-html5-preview', ['build-debug-infos'], function (done) { - Engine.buildPreview('./index.js', './bin/cocos2d-js-for-preview.js', done); -}); - -gulp.task('build-html5-preview-dev', ['build-debug-infos'], function (done) { - Engine.buildPreview('./index.js', './bin/cocos2d-js-for-preview.js', done, true); -}); - -gulp.task('build-html5', ['build-html5-preview', 'build-html5-dev', 'build-html5-min']); - -gulp.task('build-jsb-dev', ['clean-cache', 'build-debug-infos'], function (done) { - var args = process.argv.slice(3); // strip task name - var opts = {}; - if (args.indexOf('--native-renderer') !== -1) { - opts.nativeRenderer = true; - } - - Engine.buildJsb([ - './index.js', - ], './bin/cocos2d-jsb.js', [], opts, done); -}); - -gulp.task('build-jsb-min', ['clean-cache', 'build-debug-infos'], function (done) { - var args = process.argv.slice(3); // strip task name - var opts = {}; - if (args.indexOf('--native-renderer') !== -1) { - opts.nativeRenderer = true; - } - - Engine.buildJsbMin([ - './index.js', - ], './bin/cocos2d-jsb-min.js', [], opts, done); -}); - -gulp.task('build-jsb-preview', ['build-debug-infos'], function (done) { - Engine.buildJsbPreview([ - './index.js', - ], './bin/cocos2d-jsb-for-preview.js', [], done); -}); - -gulp.task('build-jsb', ['build-jsb-preview', 'build-jsb-dev', 'build-jsb-min']); - -///////// -// test // -///////// - -gulp.task('clean-test', ['clean-test-cases'], function (done) { - Del([ - './bin/cocos2d-js-extends-for-test.js', - './bin/cocos2d-js-for-test.js', - ], done); -}); - -gulp.task('clean-test-cases', function (done) { - Del('./bin/test/**/*', done); -}); - -gulp.task('build-test-cases', ['clean-test-cases'], function (done) { - Test.buildTestCase('./bin/test/', done); -}); - -gulp.task('build-test', ['clean-test', 'build-test-cases', 'build-debug-infos'], function (done) { - Test.build('./index.js', './bin/cocos2d-js-for-test.js', - '../editor/test-utils/engine-extends-entry.js', './bin/cocos2d-js-extends-for-test.js', - false, done); -}); -gulp.task('build-test-sm', ['clean-test', 'build-test-cases', 'build-debug-infos'], function (done) { - Test.build('./index.js', './bin/cocos2d-js-for-test.js', - '../editor/test-utils/engine-extends-entry.js', './bin/cocos2d-js-extends-for-test.js', - true, done); -}); - -gulp.task('unit-runner', ['build-test'], function (done) { - Test.unit('./bin', [ - './bin/cocos2d-js-for-test.js' - ], done); -}); - -gulp.task('test', ['build-test', 'unit-runner'], function (done) { - Test.test(done); -}); - -gulp.task('visual-test', ['build-test'], Shell.task([ - 'sh ./test/visual-tests/run.sh' -])); - -gulp.task('test-no-build', function (done) { - Test.test(done); -}); - -//////////// -// global // -//////////// - -gulp.task('clean-cache', function (done) { - Del(['./bin/.cache/*', '!./bin/.cache/dev/**'], done); -}); - -// fast build, only for develop -gulp.task('build-dev', ['clean-cache', 'build-html5-preview', 'build-jsb-preview'], function (done) { - Del(['./bin/cocos2d-jsb-min.js', './bin/cocos2d-jsb.js'], done); -}); - -// only build preview for html5 since it will built by editor -gulp.task('build', ['clean-cache', 'build-html5-preview', 'build-jsb']); - -// default task -gulp.task('default', ['build']); - -gulp.task('clean', function (done) { - Del('./bin/**/*', done); -}); - -//////////// -// watch // -//////////// - -gulp.task('watch-preview', function () { - Watch.preview('./index.js', './bin/cocos2d-js-for-preview.js'); -}); - -gulp.task('watch-jsb-polyfill', function () { - Watch.jsbPolyfill([ - './index.js', - ], './bin/cocos2d-jsb.js'); -}); - -gulp.task('watch-dev-files', ['watch-preview', 'watch-jsb-polyfill']); - -gulp.task('test-in-ci', function () { - const { spawn } = require('child_process'); - var gulp = process.platform === 'win32' ? 'gulp.cmd' : 'gulp'; - var child = spawn(gulp, ['test'], { - stdio: [0, 'pipe', 2] +gulp.task('build-code', gulp.series('build-debug-infos', () => { + return cp.exec(`node ./rollup/out/build-engine-cli.js --sourcemap --buildmode=universal --platform=HTML5 --physics=cannon --destination=./bin/dev/cc.js`, { + cwd: __dirname, }); - child.stdout.on('data', function (data) { - process.stdout.write(data); - if (data.toString().indexOf(' assertions failed ') !== -1) { - process.exitCode = 1; - process.exit(); - } +})); + +gulp.task('build-code-minified', gulp.series('build-debug-infos', () => { + return cp.exec(`node ./rollup/out/build-engine-cli.js --compress --sourcemap --buildmode=universal --platform=HTML5 --physics=cannon --destination=./bin/dev/cc.min.js`, { + cwd: __dirname, + }); +})); + +gulp.task('build-declarations', async () => { + const outDir = ps.join('bin', '.declarations'); + await fs.emptyDir(outDir); + return require('./scripts/generate-declarations/generate-declarations.js').generate({ + outDir, }); }); -//////////// -// API // -//////////// +gulp.task('build', gulp.parallel('build-code-minified', 'build-declarations')); -gulp.task('build-api-json', function () { - APIBuilder.generateJson(); +gulp.task('code-check', () => { + return cp.exec(`tsc --noEmit`, { + cwd: __dirname, + }); }); -gulp.task('build-3d-api', function () { - APIBuilder.generateHTMLWithLocalization(); +gulp.task('unit-tests', () => { + return cp.exec(`jest`, { + cwd: __dirname, + }); }); + +gulp.task('test', gulp.series('code-check', 'unit-tests')); + +gulp.task('build-api-json', async () => { + const APIBuilder = require('./gulp/util/api-docs-build'); + return await Promise.resolve(APIBuilder.generateJson()); +}); + +gulp.task('build-3d-api', async () => { + const APIBuilder = require('./gulp/util/api-docs-build'); + return await Promise.resolve(APIBuilder.generateHTMLWithLocalization()); +}); \ No newline at end of file diff --git a/package.json b/package.json index 246ff8c6e2..c3a68d41e7 100644 --- a/package.json +++ b/package.json @@ -10,78 +10,34 @@ "module": "index.js", "scripts": { "server": "http-server . -p 8002 -o http://127.0.0.1:8002/playground/index.html", - "build": "npm run build:min && npm run build-declaration", - "build:dev": "node ./rollup/out/build-engine-cli.js --sourcemap --buildmode=universal --platform=HTML5 --physics=cannon --destination=./bin/dev/cc.js", - "build:min": "node ./rollup/out/build-engine-cli.js --compress --sourcemap --buildmode=universal --platform=HTML5 --physics=cannon --destination=./bin/dev/cc.min.js", - "build-declaration": "node ./scripts/generate-declarations/generate-declarations-cli.js", + "build": "gulp build", + "build:dev": "gulp build-code", + "build:min": "gulp build-code-minified", + "build-declaration": "gulp build-declarations", "build-rollup": "tsc --build rollup/tsconfig.json", "postinstall": "npm run build-rollup", "build-api-json": "gulp build-api-json -i index.ts -o ./3d-api-docs/tempJson", "build-api": "npm run build-api-json && gulp build-3d-api -i index.ts -o ./3d-api-docs -j ./3d-api-docs/tempJson", - "test": "tsc --noEmit && jest", - "testWithCoverage": "jest --coverage" + "test": "gulp test" }, "repository": { "type": "git", "url": "git+https://github.com/cocos-creator/engine.git" }, "devDependencies": { - "@babel/core": "^7.8.0", - "@babel/plugin-transform-for-of": "^7.8.0", - "@babel/preset-env": "^7.8.2", - "@cocos/babel-preset-cc": "^1.0.3", + "@cocos/build-engine": "^1.0.3", "@types/fs-extra": "^5.0.4", "@types/jest": "^24.0.25", - "@types/uglify-js": "^3.0.4", "@types/yargs": "^12.0.14", "@typescript-eslint/eslint-plugin": "^1.13.0", "@typescript-eslint/parser": "^1.13.0", - "aliasify": "^2.1.0", - "async": "1.5.2", - "babel-preset-env": "^1.2.2", - "babelify": "7.3.0", - "browserify": "^16.2.3", - "chalk": "1.1.0", "commander": "^2.20.3", "dat.gui": "^0.7.5", - "del": "1.2.0", "eslint": "^6.8.0", - "event-stream": "3.3.2", - "fire-fs": "0.2.1", "fs-extra": "^7.0.1", - "fs-jetpack": "^1.1.0", - "gulp": "^3.9.1", - "gulp-babel": "6.1.2", - "gulp-cached": "1.1.0", - "gulp-concat": "2.6.0", - "gulp-fb": "0.5.1", - "gulp-header": "1.2.2", - "gulp-jshint": "1.11.2", - "gulp-mirror": "0.4.0", - "gulp-optimize-js": "^1.1.0", - "gulp-plumber": "0.6.6", - "gulp-rename": "1.2.2", - "gulp-shell": "^0.6.5", - "gulp-size": "2.1.0", - "gulp-sourcemaps": "1.5.2", - "gulp-uglify": "^3.0.0", - "gulp-util": "3.0.6", + "gulp": "^4.0.2", "http-server": "^0.11.1", "jest": "^24.8.0", - "jshint-stylish": "2.1.0", - "multipipe": "0.3.0", - "persistify": "^1.1.1", - "require-dir": "0.3.0", - "rollup": "^1.29.0", - "rollup-plugin-babel": "^4.1.0-1", - "rollup-plugin-commonjs": "10.0.1", - "rollup-plugin-json": "^3.1.0", - "rollup-plugin-multi-entry": "^2.1.0", - "rollup-plugin-node-resolve": "5.2.0", - "rollup-plugin-progress": "^1.1.1", - "rollup-plugin-terser": "^5.2.0", - "rollup-plugin-uglify": "^6.0.4", - "rollup-watch": "^4.3.1", "spectorjs": "^0.9.12", "stats.js": "^0.17.0", "tfig": "^1.2.3", @@ -92,10 +48,6 @@ "typedoc-plugin-localization": "github:cocos-creator/typedoc-plugin-localization#master", "typescript": "^3.7.2", "vconsole": "^3.3.0", - "vinyl": "1.1.0", - "vinyl-buffer": "1.0.0", - "vinyl-source-stream": "1.0.0", - "watchify": "^3.7.0", "yargs": "^12.0.5" }, "dependencies": { diff --git a/rollup/src/build-engine-cli.ts b/rollup/src/build-engine-cli.ts index 924279359d..5017dabb3c 100644 --- a/rollup/src/build-engine-cli.ts +++ b/rollup/src/build-engine-cli.ts @@ -1,7 +1,7 @@ import * as fs from 'fs-extra'; import * as ps from 'path'; import yargs from 'yargs'; -import { build, enumeratePhysicsReps, enumerateBuildModeReps, enumeratePlatformReps, IBuildOptions, IFlags, parsePhysics, parseBuildMode, enumerateModuleOptionReps, parseModuleOption, parsePlatform } from './build-engine'; +import { build, enumeratePhysicsReps, enumerateBuildModeReps, enumeratePlatformReps, IBuildOptions, IFlags, parsePhysics, parseBuildMode, enumerateModuleOptionReps, parseModuleOption, parsePlatform } from '@cocos/build-engine'; yargs.help(); yargs.option('buildmode', { @@ -67,20 +67,14 @@ if (argvFlags) { const sourceMap = yargs.argv.sourcemap === 'inline' ? 'inline' : !!yargs.argv.sourcemap; -const moduleEntries = yargs.argv._; -if (moduleEntries.length === 0) { - console.log(`No module entry specified, default module entries will be used.`); - moduleEntries.push(...getDefaultModuleEntries()); -} - const watchFiles = yargs.argv['watch-files'] as string | undefined; const options: IBuildOptions = { - moduleEntries, + engine: ps.join(__dirname, '..', '..'), + moduleEntries: yargs.argv._ as (string[] | undefined), compress: yargs.argv.compress as (boolean | undefined), outputPath: yargs.argv.destination as string, - excludes: yargs.argv.excludes as string[], - sourcemap: sourceMap, + sourceMap, flags, watchFiles: !!watchFiles, progress: yargs.argv.progress as (boolean | undefined), @@ -108,37 +102,3 @@ if (yargs.argv.platform) { await fs.writeFile(watchFiles, JSON.stringify(result.watchFiles, undefined, 2)); } })(); - -function getDefaultModuleEntries () { - type ModuleDivision = any; // import('../../scripts/module-division/tools/division-config').ModuleDivision; - type GroupItem = any; // import('../../scripts/module-division/tools/division-config').GroupItem; - type Item = any; // import('../../scripts/module-division/tools/division-config').Item; - - const isGroupItem = (item: Item): item is GroupItem => { - return 'options' in item; - }; - - const divisionConfig: ModuleDivision = require('../../scripts/module-division/division-config.json'); - const result: string[] = []; - const addEntry = (entry: string | string[]) => { - if (Array.isArray(entry)) { - result.push(...entry); - } else { - result.push(entry); - } - }; - for (const groupOrItem of divisionConfig.groupOrItems) { - const items = 'items' in groupOrItem ? groupOrItem.items : [groupOrItem]; - for (const item of items) { - if (item.required || item.default) { - if (isGroupItem(item)) { - addEntry(item.options[item.defaultOption || 0].entry); - } else { - // @ts-ignore - addEntry(item.entry); - } - } - } - } - return result; -} diff --git a/rollup/src/build-engine.ts b/rollup/src/build-engine.ts deleted file mode 100644 index 734af6448e..0000000000 --- a/rollup/src/build-engine.ts +++ /dev/null @@ -1,474 +0,0 @@ -import { existsSync } from 'fs'; -import fs from 'fs-extra'; -import { dirname, join, normalize, relative } from 'path'; -// @ts-ignore -import babel from 'rollup-plugin-babel'; -// @ts-ignore -import commonjs from 'rollup-plugin-commonjs'; -// @ts-ignore -import json from 'rollup-plugin-json'; -// @ts-ignore -import multiEntry from 'rollup-plugin-multi-entry'; -// @ts-ignore -import resolve from 'rollup-plugin-node-resolve'; -// @ts-ignore -import { uglify } from 'rollup-plugin-uglify'; -// @ts-ignore -import { excludes } from '../plugin/rollup-plugin-excludes'; -import { terser } from 'rollup-plugin-terser'; -// @ts-ignore -import babelPresetEnv from '@babel/preset-env'; -import babelPresetCc from '@cocos/babel-preset-cc'; -import { writeFile, ensureDir } from 'fs-extra'; -import * as rollup from 'rollup'; -// @ts-ignore -import rpProgress from 'rollup-plugin-progress'; - -interface IBaseOptions { - moduleEntries: string[]; - - /** - * 指定输出路径。 - * 你仍应该自己写入生成代码到此文件中。 - */ - outputPath: string; - - /** - * 输出模块格式。 - * @default ModuleOption.system - */ - moduleFormat?: ModuleOption; - - /** - * 排除的模块。 - * @default [] - */ - excludes?: string[]; - - /** - * 是否对生成结果进行压缩。 - * @default false - */ - compress?: boolean; - - /** - * 是否生成 source map。 - * 若为 `inline` 则生成内联的 source map。 - * @default false - */ - sourcemap?: boolean | 'inline'; - - /** - * 若 `sourcemap` 为 `true`,此选项指定了 source map 的路径。 - * 此选项只是为了在生成的结果代码中说明 source map 的相对位置, - * 所以你仍应该自己写入 source map 的内容到此文件中。 - * @default `${outputPath.map}` - */ - sourcemapFile?: string; - - watchFiles?: boolean; - - progress?: boolean; -} - -interface IAdvancedOptions extends IBaseOptions { - globalDefines: object; -} - -export interface IBuildOptions extends IBaseOptions { - /** - * 构建模式。 - */ - mode?: Mode; - - /** - * 目标平台。 - */ - platform?: Platform; - - /** - * 引擎标志。 - */ - flags?: IFlags; -} - -export async function build (options: IBuildOptions) { - _checkPhysicsFlag(options); - _ensureUniqueModules(options); - - const globalDefines = getGlobalDefs(options); - return await _internalBuild(Object.assign(options, {globalDefines})); -} - -function resolveModuleEntry (moduleEntry: string) { - return normalize(`${__dirname}/../../exports/${moduleEntry}.ts`); -} - -interface IModuleInfo { - requiredFlags: string[]; -} - -const moduleInfoTable: Record = { - 'physics-builtin': { - requiredFlags: ['CC_PHYSICS_BUILTIN'], - }, - 'physics-cannon': { - requiredFlags: ['CC_PHYSICS_CANNON'], - }, - 'physics-ammo': { - requiredFlags: ['CC_PHYSICS_AMMO'], - }, -}; - -function _checkPhysicsFlag (options: IBuildOptions) { - // const physicsModulesMap = { - // [Physics.builtin]: `physics-builtin`, - // [Physics.cannon]: `physics-cannon`, - // [Physics.ammo]: `physics-ammo`, - // }; - // const allowedPhysicsModules = Object.values(physicsModulesMap); - - // if (options.moduleEntries.some( - // (moduleEntry) => allowedPhysicsModules.includes(moduleEntry))) { - // console.warn( - // `You shall not specify physics module explicitly. ` + - // `Use 'physics' option instead.`); - // options.moduleEntries = options.moduleEntries.filter( - // (moduleEntry) => !allowedPhysicsModules.includes(moduleEntry)); - // } - - // const physics = options.physics === undefined ? Physics.cannon : options.physics; - // options.moduleEntries.push(physicsModulesMap[physics]); - - // // direct push physics-framework for now - // options.moduleEntries.push(`physics-framework`); -} - -function _ensureUniqueModules (options: IBuildOptions) { - const uniqueModuleEntries: string[] = []; - for (const moduleEntry of options.moduleEntries) { - if (uniqueModuleEntries.indexOf(moduleEntry) < 0) { - uniqueModuleEntries.push(moduleEntry); - } - } - options.moduleEntries = uniqueModuleEntries; -} - -async function _internalBuild (options: IAdvancedOptions) { - console.log(`Build-engine options: ${JSON.stringify(options, undefined, 2)}`); - const doUglify = !!options.compress; - - let format: rollup.ModuleFormat = 'iife'; - switch (options.moduleFormat) { - case ModuleOption.cjs: - format = 'cjs'; - break; - case ModuleOption.esm: - format = 'esm'; - break; - case ModuleOption.system: - format = 'system'; - break; - } - - const rollupPlugins: rollup.Plugin[] = [ - multiEntry(), - - excludes({ - modules: options.excludes, - }), - - resolve({ - extensions: ['.js', '.ts', '.json'], - }), - - json({ - preferConst: true, - }), - - babel({ - extensions: ['.js', '.ts'], - highlightCode: true, - ignore: [ - 'node_modules/@cocos/ammo/**', - 'node_modules/@cocos/cannon/**', - ], - plugins: [ - ['@babel/plugin-transform-for-of', { - loose: true, - }], - ], - presets: [ - babelPresetEnv, - babelPresetCc, - ], - }), - - commonjs({ - namedExports: { - '@cocos/ammo': ['Ammo'], - '@cocos/cannon': ['CANNON'], - }, - }), - ]; - - if (options.progress) { - rollupPlugins.unshift(rpProgress()); - } - - /** adapt: reduce_funcs not suitable for ammo.js */ - const defines = options.globalDefines as IGlobaldefines; - const isReduceFuncs = !defines.CC_PHYSICS_AMMO; - - rollupPlugins.push(terser({ - compress: { - global_defs: options.globalDefines, - reduce_funcs: isReduceFuncs - }, - mangle: doUglify, - keep_fnames: !doUglify, - output: { - beautify: !doUglify, - }, - sourcemap: !!options.sourcemap, - - // https://github.com/rollup/rollup/issues/3315 - // We only do this for CommonJS. - // Especially, we cannot do this for IIFE. - toplevel: format === 'cjs', - })); - - const outputPath = options.outputPath; - const sourcemapFile = options.sourcemapFile || `${options.outputPath}.map`; - - const moduleEntries = options.moduleEntries.map(resolveModuleEntry).filter((moduleEntry) => { - const exists = existsSync(moduleEntry); - if (exists) { - return true; - } else { - console.warn(`Cannot find engine module ${moduleEntry}. it's ignored.`); - return false; - } - }); - - const rollupBuild = await rollup.rollup({ - input: moduleEntries, - plugins: rollupPlugins, - }); - - let watchFiles: Record | undefined; - if (options.watchFiles) { - watchFiles = {}; - for (const watchFile of rollupBuild.watchFiles) { - try { - const stat = await fs.stat(watchFile); - watchFiles[watchFile] = stat.mtimeMs; - } catch { - // the `watchFiles` may contain non-fs modules. - } - } - } - - const generated = await rollupBuild.generate({ - format, - sourcemap: options.sourcemap, - sourcemapFile, - name: (format === 'iife' ? 'ccm' : undefined), - }); - - const chunk0 = generated.output[0]; - if (options.sourcemap === true && chunk0.map) { - const sourceMappingUrl = relative(dirname(outputPath), sourcemapFile); - return { - code: `${chunk0.code}\n//# sourceMappingURL=${sourceMappingUrl}`, - map: chunk0.map.toString(), - watchFiles, - }; - } else if (options.sourcemap === 'inline' && chunk0.map) { - return { - code: `${chunk0.code}\n//# sourceMappingURL=${chunk0.map.toUrl()}`, - watchFiles, - }; - } else { - return { - code: chunk0.code, - watchFiles, - }; - } -} - -export enum Platform { - HTML5, - WECHAT, - ALIPAY, - BAIDU, - XIAOMI, - OPPO, - VIVO, - HUAWEI, - NATIVE, - COCOSPLAY, -} - -export function enumeratePlatformReps () { - return Object.values(Platform).filter((value) => typeof value === 'string') as Array; -} - -export function parsePlatform (rep: string) { - return Reflect.get(Platform, rep); -} - -export enum Mode { - universal, - editor, - preview, - build, - test, -} - -export function enumerateBuildModeReps () { - return Object.values(Mode).filter((value) => typeof value === 'string') as Array; -} - -export function parseBuildMode (rep: string) { - return Reflect.get(Mode, rep); -} - -export enum Physics { - cannon, - ammo, - builtin, -} - -export function enumeratePhysicsReps () { - return Object.values(Physics).filter((value) => typeof value === 'string'); -} - -export function parsePhysics (rep: string) { - return Reflect.get(Physics, rep); -} - -export enum ModuleOption { - esm, - cjs, - system, - iife, -} - -export function enumerateModuleOptionReps () { - return Object.values(ModuleOption).filter((value) => typeof value === 'string') as Array; -} - -export function parseModuleOption (rep: string) { - return Reflect.get(ModuleOption, rep); -} - -export interface IFlags { - jsb?: boolean; - runtime?: boolean; - wechatgame?: boolean; - qqplay?: boolean; - debug?: boolean; - nativeRenderer?: boolean; -} - -interface IGlobaldefines { - // BuildMode macros - CC_EDITOR?: boolean; - CC_PREVIEW?: boolean; - CC_BUILD?: boolean; - CC_TEST?: boolean; - - // Platform macros - CC_HTML5?: boolean; - CC_WECHAT?: boolean; - CC_ALIPAY?: boolean; - CC_BAIDU?: boolean; - CC_XIAOMI?: boolean; - CC_OPPO?: boolean; - CC_VIVO?: boolean; - CC_HUAWEI?: boolean; - CC_NATIVE?: boolean; - CC_COCOSPLAY?: boolean; - - // engine use platform macros - CC_RUNTIME_BASED?: boolean; - CC_MINIGAME?: boolean; - CC_JSB?: boolean; - - // Flag macros - CC_DEBUG?: boolean; - - // Debug macros - CC_DEV?: boolean; - CC_SUPPORT_JIT?: boolean; - - // Physics macros - CC_PHYSICS_CANNON?: boolean; - CC_PHYSICS_AMMO?: boolean; - CC_PHYSICS_BUILTIN?: boolean; -} - -function getGlobalDefs (options: IBuildOptions): object { - const buildmode = options.mode || Mode.universal; - const platform = options.platform; - const flags = options.flags; - - const BUILDMODE_MACROS = ['CC_EDITOR', 'CC_PREVIEW', 'CC_BUILD', 'CC_TEST']; - const PLATFORM_MACROS = ['CC_HTML5', 'CC_WECHAT', 'CC_ALIPAY', 'CC_BAIDU', 'CC_XIAOMI', 'CC_OPPO', 'CC_VIVO', 'CC_HUAWEI', 'CC_NATIVE', 'CC_COCOSPLAY']; - const FLAGS = ['debug']; - - const buildmodeMacro = ('CC_' + Mode[buildmode]).toUpperCase(); - if (BUILDMODE_MACROS.indexOf(buildmodeMacro) === -1 && buildmode !== Mode.universal) { - throw new Error(`Unknown buildmode ${buildmode}.`); - } - const platformMacro = ('CC_' + Platform[platform!]).toUpperCase(); - if ( PLATFORM_MACROS.indexOf(platformMacro) === -1) { - throw new Error(`Unknown platform ${platform}.`); - } - const result: IGlobaldefines = {}; - for (const macro of BUILDMODE_MACROS) { - result[macro as keyof IGlobaldefines] = (macro === buildmodeMacro); - } - - for (const macro of PLATFORM_MACROS) { - result[macro as keyof IGlobaldefines] = (macro === platformMacro); - } - - if (flags) { - for (const flag in flags) { - if (flags.hasOwnProperty(flag) && flags[flag as keyof IFlags]) { - if (FLAGS.indexOf(flag) === -1) { - throw new Error('Unknown flag: ' + flag); - } - } - } - } - for (const flag of FLAGS) { - const macro = 'CC_' + flag.toUpperCase(); - result[macro as keyof IGlobaldefines] = !!(flags && flags[flag as keyof IFlags]); - } - - result.CC_RUNTIME_BASED = false; - result.CC_MINIGAME = false; - result.CC_DEV = result.CC_EDITOR || result.CC_PREVIEW || result.CC_TEST; - result.CC_DEBUG = result.CC_DEBUG || result.CC_DEV; - result.CC_RUNTIME_BASED = result.CC_OPPO || result.CC_VIVO || result.CC_HUAWEI || result.CC_COCOSPLAY; - result.CC_MINIGAME = result.CC_WECHAT || result.CC_ALIPAY || result.CC_XIAOMI || result.CC_BAIDU; - result.CC_JSB = result.CC_NATIVE || result.CC_RUNTIME_BASED; - result.CC_SUPPORT_JIT = !(result.CC_MINIGAME || result.CC_RUNTIME_BASED); - result.CC_PHYSICS_BUILTIN = false; - result.CC_PHYSICS_CANNON = false; - result.CC_PHYSICS_AMMO = false; - - for (const moduleEntry of options.moduleEntries) { - if (moduleEntry in moduleInfoTable) { - for (const flag of moduleInfoTable[moduleEntry].requiredFlags) { - // @ts-ignore - result[flag] = true; - } - } - } - - return result; -}