Remove unnecessary NPM dependencies and gulp logic; bump gulp to fit Node v12+; Use @cocos/build-engine (#6121)

This commit is contained in:
Leslie Leigh (李的序)
2020-02-12 16:28:09 +08:00
committed by GitHub
parent 0ab3bc878e
commit 01b79164cb
13 changed files with 56 additions and 1699 deletions
-33
View File
@@ -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<entry.length;i++) newRequire(entry[i]);
// Override the current require with this new one
return newRequire;
})
-295
View File
@@ -1,295 +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.
****************************************************************************/
'use strict';
const Utils = require('../util/utils');
const createBundler = require('../util/create-bundler');
const Path = require('path');
const Source = require('vinyl-source-stream');
const Gulp = require('gulp');
const Buffer = require('vinyl-buffer');
const Sourcemaps = require('gulp-sourcemaps');
const EventStream = require('event-stream');
const Chalk = require('chalk');
const HandleErrors = require('../util/handleErrors');
const Optimizejs = require('gulp-optimize-js');
var jsbSkipModules = [
// modules need to skip in jsb
];
var jsbAliasify = {
replacements: {
},
verbose: false
};
exports.buildDebugInfos = require('./buildDebugInfos');
exports.buildCocosJs = function (sourceFile, outputFile, excludes, opt_macroFlags, callback, createMap) {
if (typeof opt_macroFlags === 'function') {
callback = opt_macroFlags;
opt_macroFlags = null;
}
var opts = {
sourcemaps: createMap !== false
};
var outDir = Path.dirname(outputFile);
var outFile = Path.basename(outputFile);
var bundler = createBundler(sourceFile, opts);
excludes && excludes.forEach(function (file) {
bundler.exclude(file);
});
bundler = bundler.bundle();
bundler = bundler.pipe(Source(outFile));
bundler = bundler.pipe(Buffer());
if (createMap) {
bundler = bundler.pipe(Sourcemaps.init({loadMaps: true}));
}
bundler = bundler.pipe(Utils.uglify('build', Object.assign({ debug: true }, opt_macroFlags)));
bundler = bundler.pipe(Optimizejs({
sourceMap: false
}));
if (createMap) {
bundler = bundler.pipe(Sourcemaps.write('./', {
sourceRoot: './',
includeContent: true,
addComment: true
}));
}
bundler = bundler.pipe(Gulp.dest(outDir));
return bundler.on('end', callback);
};
exports.buildCocosJsMin = function (sourceFile, outputFile, excludes, opt_macroFlags, callback, createMap) {
if (typeof opt_macroFlags === 'function') {
callback = opt_macroFlags;
opt_macroFlags = null;
}
var opts = {
sourcemaps: createMap !== false
};
var outDir = Path.dirname(outputFile);
var outFile = Path.basename(outputFile);
var bundler = createBundler(sourceFile, opts);
excludes && excludes.forEach(function (file) {
bundler.exclude(file);
});
bundler.exclude(Path.resolve(__dirname, '../../DebugInfos.json'));
var Size = null;
try {
Size = require('gulp-size');
} catch (error) {
Size = null;
}
if (Size) {
var rawSize = Size({ gzip: false, pretty: false, showTotal: false, showFiles: false });
var zippedSize = Size({ gzip: true, pretty: false, showTotal: false, showFiles: false });
}
bundler = bundler.bundle();
bundler = bundler.pipe(Source(outFile));
bundler = bundler.pipe(Buffer());
if (createMap) {
console.error('Can not use sourcemap with optimize-js');
bundler = bundler.pipe(Sourcemaps.init({loadMaps: true}));
}
bundler = bundler.pipe(Utils.uglify('build', opt_macroFlags));
bundler = bundler.pipe(Optimizejs({
sourceMap: false
}));
if (Size) {
bundler = bundler.pipe(rawSize);
bundler = bundler.pipe(zippedSize);
bundler = bundler.pipe(EventStream.through(null, function () {
var raw = rawSize.size;
var zipped = zippedSize.size;
var percent = ((zipped / raw) * 100).toFixed(2);
console.log(`Size of ${outputFile}: minimized: ${Chalk.cyan(raw)}B zipped: ${Chalk.cyan(zipped)}B, compression ratio: ${percent}%`);
this.emit('end');
}));
}
if (createMap) {
bundler = bundler.pipe(Sourcemaps.write('./', {
sourceRoot: './',
includeContent: true,
addComment: true
}));
}
bundler = bundler.pipe(Gulp.dest(outDir));
return bundler.on('end', callback);
};
exports.buildPreview = function (sourceFile, outputFile, callback, devMode) {
var cacheDir = devMode && Path.resolve(Path.dirname(outputFile), '.cache/preview-compile-cache');
var outFile = Path.basename(outputFile);
var outDir = Path.dirname(outputFile);
var bundler = createBundler(sourceFile, {
cacheDir: cacheDir,
sourcemaps: !devMode
});
var bundler = bundler
.bundle()
.on('error', HandleErrors.handler)
.pipe(HandleErrors())
.pipe(Source(outFile))
.pipe(Buffer());
if (!devMode) {
bundler = bundler
.pipe(Sourcemaps.init({loadMaps: true}))
.pipe(Utils.uglify('preview'))
.pipe(Optimizejs({
sourceMap: false
}))
.pipe(Sourcemaps.write('./', {
sourceRoot: '../',
includeContent: false,
addComment: true
}));
}
bundler
.pipe(Gulp.dest(outDir))
.on('end', callback);
};
exports.buildJsbPreview = function (sourceFile, outputFile, excludes, callback) {
var FixJavaScriptCore = require('../util/fix-jsb-javascriptcore');
var outFile = Path.basename(outputFile);
var outDir = Path.dirname(outputFile);
excludes = excludes.concat(jsbSkipModules);
var bundler = createBundler(sourceFile);
excludes.forEach(function (module) {
bundler.exclude(require.resolve(module));
});
bundler.bundle()
.on('error', HandleErrors.handler)
.pipe(HandleErrors())
.pipe(Source(outFile))
.pipe(Buffer())
.pipe(FixJavaScriptCore())
.pipe(Utils.uglify('preview', { jsb: true }))
.pipe(Optimizejs({
sourceMap: false
}))
.pipe(Gulp.dest(outDir))
.on('end', callback);
};
exports.buildJsb = function (sourceFile, outputFile, excludes, opt_macroFlags, callback, createMap) {
if (typeof opt_macroFlags === 'function') {
callback = opt_macroFlags;
opt_macroFlags = null;
}
var opts = {
sourcemaps: createMap !== false
};
if (opt_macroFlags && opt_macroFlags.nativeRenderer) {
opts.aliasifyConfig = jsbAliasify;
}
var FixJavaScriptCore = require('../util/fix-jsb-javascriptcore');
var outFile = Path.basename(outputFile);
var outDir = Path.dirname(outputFile);
var bundler = createBundler(sourceFile, opts);
excludes = excludes.concat(jsbSkipModules);
excludes.forEach(function (module) {
bundler.exclude(require.resolve(module));
});
bundler.bundle()
.on('error', HandleErrors.handler)
.pipe(HandleErrors())
.pipe(Source(outFile))
.pipe(Buffer())
.pipe(FixJavaScriptCore())
.pipe(Utils.uglify('build', Object.assign({ jsb: true, debug: true }, opt_macroFlags)))
.pipe(Optimizejs({
sourceMap: false
}))
.pipe(Gulp.dest(outDir))
.on('end', callback);
};
exports.buildJsbMin = function (sourceFile, outputFile, excludes, opt_macroFlags, callback, createMap) {
if (typeof opt_macroFlags === 'function') {
callback = opt_macroFlags;
opt_macroFlags = null;
}
var opts = {
sourcemaps: createMap !== false
};
if (opt_macroFlags && opt_macroFlags.nativeRenderer) {
opts.aliasifyConfig = jsbAliasify;
}
var FixJavaScriptCore = require('../util/fix-jsb-javascriptcore');
var outFile = Path.basename(outputFile);
var outDir = Path.dirname(outputFile);
var bundler = createBundler(sourceFile, opts);
excludes = excludes.concat(jsbSkipModules);
excludes.forEach(function (module) {
bundler.exclude(require.resolve(module));
});
bundler.exclude(Path.resolve(__dirname, '../../DebugInfos.json'));
bundler.bundle()
.on('error', HandleErrors.handler)
.pipe(HandleErrors())
.pipe(Source(outFile))
.pipe(Buffer())
.pipe(FixJavaScriptCore())
.pipe(Utils.uglify('build', Object.assign({ jsb: true }, opt_macroFlags)))
.pipe(Optimizejs({
sourceMap: false
}))
.pipe(Gulp.dest(outDir))
.on('end', callback);
};
exports.jsbSkipModules = jsbSkipModules;
-146
View File
@@ -1,146 +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.
****************************************************************************/
const UGLIFY = false;
'use strict';
const Path = require('path');
const Fs = require('fs');
const Source = require('vinyl-source-stream');
const Gulp = require('gulp');
const Fb = require('gulp-fb');
const Babel = require('gulp-babel');
const Buffer = require('vinyl-buffer');
const HandleErrors = require('../util/handleErrors');
const Es = require('event-stream');
const Sourcemaps = require('gulp-sourcemaps');
const Utils = require('../util/utils');
const createBundler = require('../util/create-bundler');
exports.build = function (sourceFile, outputFile, sourceFileForExtends, outputFileForExtends, sourcemaps, callback) {
var cacheDir = Path.resolve(Path.dirname(outputFile), '.cache/test-compile-cache');
var engine = createBundler(sourceFile, {
sourcemaps: sourcemaps,
cacheDir: cacheDir
})
.bundle()
.on('error', HandleErrors.handler)
.pipe(HandleErrors())
.pipe(Source(Path.basename(outputFile)))
.pipe(Buffer());
if (UGLIFY) {
if (sourcemaps) {
engine = engine.pipe(Sourcemaps.init({loadMaps: true}));
}
// remove `...args` used in CC_JSB
engine = engine.pipe(Utils.uglify('test'));
if (sourcemaps) {
engine = engine.pipe(Sourcemaps.write('./', {
sourceRoot: '../',
includeContent: false,
addComment: true
}));
}
}
engine = engine.pipe(Gulp.dest(Path.dirname(outputFile)));
if (Fs.existsSync(sourceFileForExtends)) {
var engineExtends = createBundler(sourceFileForExtends,
{
sourcemaps: sourcemaps,
babelifyOpt: {
presets: ['env'],
ast: false,
babelrc: false,
highlightCode: false,
sourceMaps: true,
compact: false
},
cacheDir: cacheDir
})
.bundle()
.on('error', HandleErrors.handler)
.pipe(HandleErrors())
.pipe(Source(Path.basename(outputFileForExtends)))
.pipe(Buffer())
.pipe(Gulp.dest(Path.dirname(outputFileForExtends)));
Es.merge(engine, engineExtends).on('end', callback);
}
else {
engine.on('end', callback);
}
};
exports.unit = function (outDir, libs, callback) {
var title = 'CocosCreator Engine Test Suite';
if (Fs.existsSync('./bin/cocos2d-js-extends-for-test.js')) {
libs.push('./bin/cocos2d-js-extends-for-test.js');
title += ' (Editor Extends Included)';
}
return Gulp.src(['test/qunit/unit-es5/**/*.js', './bin/test/**/*.js'], { read: false, base: './' })
.pipe(Fb.toFileList())
.pipe(Fb.generateRunner('test/qunit/lib/qunit-runner.html', outDir, title, libs))
.pipe(Gulp.dest(outDir))
.on('end', callback);
};
exports.test = function (callback) {
var qunit;
try {
qunit = require('gulp-qunit');
} catch (e) {
console.error('Please run "npm install gulp-qunit" before running "gulp test".');
throw e;
}
return Gulp.src('bin/qunit-runner.html')
.pipe(qunit({ timeout: 5 }))
.on('end', callback);
};
exports.buildTestCase = function (outDir, callback) {
return Gulp.src('test/qunit/unit/**/*.js')
.pipe(Babel({
presets: ['env'],
plugins: [
// make sure that transform-decorators-legacy comes before transform-class-properties.
'transform-decorators-legacy',
'transform-class-properties',
],
ast: false,
babelrc: false,
highlightCode: false,
sourceMaps: true,
compact: false
}))
.pipe(Gulp.dest(outDir))
.on('end', callback);
};
-108
View File
@@ -1,108 +0,0 @@
var Watchify = require('watchify');
var Browserify = require('browserify');
var Fs = require('fs');
var Path = require('path');
var through = require('through');
var Engine = require('./engine');
// var source = require('vinyl-source-stream');
// var buffer = require('vinyl-buffer');
// var sourcemaps = require('gulp-sourcemaps');
function watchFile(opts) {
var bundler = new Browserify(opts.entries, {
cache: {},
packageCache: {},
debug: true,
detectGlobals: false, // dont insert `process`, `global`, `__filename`, and `__dirname`
bundleExternal: false, // dont bundle external modules
plugin: [Watchify]
});
bundler.on('update', bundle);
if (opts.skips) {
var skips = opts.skips;
for (var i = 0; i < skips.length; ++i) {
var file = require.resolve(skips[i]);
bundler.ignore(file);
}
}
function bundle() {
var name = new Date().toTimeString() + ' : browserify for ' + opts.dest + '. ';
console.time(name);
// append prefix to index.js
var prefix = '';
if (opts.prefix) {
if (typeof opts.prefix === 'function') {
prefix = opts.prefix();
}
else if (typeof opts.prefix === 'string') {
prefix = opts.prefix;
}
}
bundler.transform(function (file) {
var data = '';
if (Path.basename(file) === 'index.js') {
data += prefix;
}
return through(write, end);
function write (buf) { data += buf; }
function end () {
this.queue(data);
this.queue(null);
}
return;
});
// do bundle
var b = bundler.bundle();
b.on('end', function () {
console.timeEnd(name);
});
b = b.pipe(Fs.createWriteStream(opts.dest));
// fixed chinese character in source maps
// b = b.pipe(source(Path.basename(opts.dest)))
// .pipe(buffer())
// .pipe(sourcemaps.init({loadMaps: true}))
// .pipe(sourcemaps.write('./'))
// .pipe(gulp.dest(Path.dirname(opts.dest)));
return b;
}
return bundle();
}
exports.preview = function (sourceFile, outputFile) {
return watchFile({
entries: sourceFile,
dest: outputFile,
prefix: 'CC_DEV = true;\n'
});
};
exports.jsbPolyfill = function (sourceFile, outputFile) {
return watchFile({
entries: sourceFile,
dest: outputFile,
prefix: function () {
var prefix = 'CC_DEV = true;\n';
prefix += 'CC_JSB = true;\n';
return prefix;
},
skips: Engine.jsbSkipModules
});
};
-1
View File
@@ -1,6 +1,5 @@
const { spawn, spawnSync } = require('child_process');
const fs = require('fs');
let program = require('commander');
program
.version('1.0.0')
-137
View File
@@ -1,137 +0,0 @@
'use strict';
const Path = require('path');
allowReturnOutsideFunctionInBrowserifyTransform();
const Fs = require('fs');
const preludePath = Path.resolve(__dirname, '../browserify_prelude.js');
const prelude = Fs.readFileSync(preludePath, 'utf8');
function allowReturnOutsideFunctionInBrowserifyTransform () {
var paths = [
'browserify/node_modules/syntax-error/node_modules/acorn',
'syntax-error/node_modules/acorn',
'acorn'
];
function patch (path) {
var acorn = require(path);
var parse = acorn.parse;
if (typeof parse === 'function') {
if (acorn.parse.name !== 'monkeyPatchedParse') {
acorn.parse = function monkeyPatchedParse(input, options) {
if (options) {
options.allowReturnOutsideFunction = true;
}
else {
options = {
allowReturnOutsideFunction: true
};
}
return parse(input, options);
};
}
}
else {
console.error('Can not find acorn.parse to patch');
}
}
var patched = false;
for (var i = 0; i < paths.length; i++) {
try {
patch(paths[i]);
patched = true;
}
catch (e) {
}
}
if (!patched) {
console.error('Can not find acorn to patch');
}
}
/*
* @param [options.sourcemaps = true]
* @param [options.babelifyOpt]
* @param [options.aliasifyConfig]
*/
module.exports = function createBundler(entryFiles, options) {
// https://github.com/substack/node-browserify#methods
var browserifyOpt = {
entries: [].concat(entryFiles),
debug: (options && 'sourcemaps' in options) ? options.sourcemaps : true,
detectGlobals: false, // dont insert `process`, `global`, `__filename`, and `__dirname`
bundleExternal: false, // dont bundle external modules
//standalone: 'engine-framework',
//basedir: tempScriptDir
// define custom prelude to optimize script evaluate time
prelude: prelude,
preludePath: Path.relative(process.cwd(), preludePath),
};
// var presets = [
// [ 'es2015', { loose: true } ],
// ];
var plugins = [
// https://babeljs.io/docs/plugins/transform-es2015-shorthand-properties/
'babel-plugin-transform-es2015-shorthand-properties',
// https://babeljs.io/docs/plugins/transform-es2015-template-literals/
'babel-plugin-transform-es2015-template-literals',
// http://babeljs.io/docs/plugins/transform-es2015-block-scoping/
'babel-plugin-transform-es2015-block-scoping',
// < 6.16.0
[ 'babel-plugin-parser-opts', { allowReturnOutsideFunction: true } ]
];
var Babelify;
try {
Babelify = require('babelify');
} catch (e) {
console.error('Please run "npm install babelify".');
throw e;
}
var aliasify;
try {
aliasify = require('aliasify');
} catch (e) {
console.error('Please run "npm install aliasify".');
throw e;
}
var b;
if (options && options.cacheDir) {
// https://github.com/royriojas/persistify
const Persistify = require('persistify');
b = Persistify(browserifyOpt, {
recreate: false,
cacheId: require('../../package.json').version + entryFiles,
cacheDir: options.cacheDir
});
}
else {
const Browserify = require('browserify');
b = new Browserify(browserifyOpt);
}
return b
.exclude(Path.join(__dirname, '../../package.json'))
.transform(Babelify, (options && options.babelifyOpt) || {
// presets: presets,
plugins: plugins,
// >= 6.16.0
// parserOpts: {
// allowReturnOutsideFunction: true,
// },
ast: false,
babelrc: false,
highlightCode: false,
sourceMaps: true,
compact: false
})
.transform(aliasify, (options && options.aliasifyConfig) || {});
};
-40
View File
@@ -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);
});
};
-52
View File
@@ -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;
-145
View File
@@ -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));
};
+45 -169
View File
@@ -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());
});
+7 -55
View File
@@ -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": {
+4 -44
View File
@@ -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;
}
-474
View File
@@ -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<string, IModuleInfo> = {
'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<string, number> | 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<keyof typeof Platform>;
}
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<keyof typeof Mode>;
}
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<keyof typeof ModuleOption>;
}
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;
}