build-easy
Version:
library build tool.
285 lines (218 loc) • 10.6 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.build = build;
function _chokidar() {
const data = _interopRequireDefault(require("@build-easy/bundles/model/chokidar"));
_chokidar = function _chokidar() {
return data;
};
return data;
}
function _vinylFs() {
const data = _interopRequireDefault(require("@build-easy/bundles/model/vinyl-fs"));
_vinylFs = function _vinylFs() {
return data;
};
return data;
}
function _figures() {
const data = _interopRequireDefault(require("@build-easy/bundles/model/figures"));
_figures = function _figures() {
return data;
};
return data;
}
function _findUp() {
const data = _interopRequireDefault(require("@build-easy/bundles/model/find-up"));
_findUp = function _findUp() {
return data;
};
return data;
}
function _rimraf() {
const data = _interopRequireDefault(require("@build-easy/bundles/model/rimraf"));
_rimraf = function _rimraf() {
return data;
};
return data;
}
function _chalk() {
const data = _interopRequireDefault(require("@build-easy/bundles/model/chalk"));
_chalk = function _chalk() {
return data;
};
return data;
}
function _path() {
const data = _interopRequireDefault(require("path"));
_path = function _path() {
return data;
};
return data;
}
function _fs() {
const data = _interopRequireDefault(require("fs"));
_fs = function _fs() {
return data;
};
return data;
}
var _host = require("./host");
var _getUserConfig = _interopRequireDefault(require("./getUserConfig"));
var _configSchema = _interopRequireDefault(require("./configSchema"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
const configFileNames = ['build.easy.ts', 'build.easy.js'];
const extSignals = ['SIGINT', 'SIGQUIT', 'SIGTERM'];
const cache = {};
const getUserConfig = cwd => (0, _getUserConfig.default)({
cwd,
schema: _configSchema.default,
configFileNames
});
const defaultConfig = {
entry: 'src',
output: 'lib',
target: 'browser',
moduleType: 'esm',
sourcemap: false,
packageDirName: 'packages'
};
function compile(options) {
const watch = options.watch,
currentDirPath = options.currentDirPath,
currentConfig = options.currentConfig,
cwd = options.cwd;
const _ref = currentConfig,
entry = _ref.entry,
output = _ref.output,
sourcemap = _ref.sourcemap,
lessOptions = _ref.lessOptions,
moduleType = _ref.moduleType,
alias = _ref.alias,
afterHook = _ref.afterHook,
beforeReadWriteStream = _ref.beforeReadWriteStream,
afterReadWriteStream = _ref.afterReadWriteStream,
injectVueCss = _ref.injectVueCss,
inputPatterns = _ref.patterns,
tsCompilerOptions = _ref.tsCompilerOptions;
const currentEntryPath = _path().default.join(currentDirPath, entry);
const currentOutputPath = _path().default.join(currentDirPath, output);
_rimraf().default.sync(currentOutputPath);
let patterns = [_path().default.join(currentEntryPath, '**/*'), `!${_path().default.join(currentEntryPath, '**/*.mdx')}`, `!${_path().default.join(currentEntryPath, '**/*.md')}`, `!${_path().default.join(currentEntryPath, '**/demos{,/**}')}`, `!${_path().default.join(currentEntryPath, '**/demo{,/**}')}`, `!${_path().default.join(currentEntryPath, '**/fixtures{,/**}')}`, `!${_path().default.join(currentEntryPath, '**/__snapshots__{,/**}')}`, `!${_path().default.join(currentEntryPath, '**/__test__{,/**}')}`, `!${_path().default.join(currentEntryPath, '**/__tests__{,/**}')}`, `!${_path().default.join(currentEntryPath, '**/*.+(test|e2e|spec).+(js|jsx|ts|tsx)')}`, `!${_path().default.join(currentEntryPath, '**/*.snap')}`];
if (inputPatterns) {
patterns = inputPatterns(patterns, currentEntryPath);
}
function createStream(options) {
const patterns = options.patterns,
currentEntryDirPath = options.currentEntryDirPath,
currentOutputDirPath = options.currentOutputDirPath;
return _vinylFs().default.src(patterns, {
base: currentEntryDirPath,
allowEmpty: true
}).pipe((0, _host.enableSourcemap)(sourcemap)).pipe((0, _host.enablePlumber)(watch)).pipe((0, _host.enablefileCache)(cache)).pipe((0, _host.applyBeforeHook)(beforeReadWriteStream)).pipe((0, _host.compileAlias)(alias)).pipe((0, _host.compileVueSfc)(injectVueCss)).pipe((0, _host.compileLess)(lessOptions)).pipe((0, _host.hackSaveFile)()).pipe((0, _host.compileDeclaration)(currentDirPath, cwd, tsCompilerOptions)).pipe((0, _host.hackGetFile)(moduleType, output)).pipe((0, _host.compileJsOrTs)(currentConfig, currentEntryDirPath)).pipe((0, _host.applyAfterHook)(afterReadWriteStream)).pipe((0, _host.modifySourcemap)(sourcemap)).pipe((0, _host.logger)()).pipe(_vinylFs().default.dest(currentOutputDirPath));
}
return new Promise(resolve => {
const streamOptions = {
patterns,
currentEntryDirPath: currentEntryPath,
currentOutputDirPath: currentOutputPath
};
createStream(streamOptions).on('end', () => {
afterHook && afterHook();
if (watch) {
console.log(`${_chalk().default.blue(_figures().default.info)} ${_chalk().default.green('Start watching directory!')}`);
const watcher = _chokidar().default.watch(patterns, {
ignoreInitial: true,
awaitWriteFinish: {
stabilityThreshold: 200
}
});
const eventLoger = (evnet, fullEnterPath) => {
console.log(`${_chalk().default.blue(_figures().default.info, evnet.charAt(0).toUpperCase() + evnet.slice(1))} ${fullEnterPath.replace(currentDirPath, '').slice(1)}`);
};
watcher.on('all', (evnet, fullEnterPath) => {
if (!_fs().default.existsSync(fullEnterPath)) {
eventLoger(evnet, fullEnterPath);
const fullOutputPath = fullEnterPath.replace(entry, output);
_rimraf().default.sync(fullOutputPath.replace('.ts', '.js'));
_rimraf().default.sync(fullOutputPath.replace('.ts', '.d.ts'));
return;
}
if (_fs().default.statSync(fullEnterPath).isFile()) {
const content = _fs().default.readFileSync(fullEnterPath, 'utf-8'); // Cache files to reduce unnecessary compilation
if (cache[fullEnterPath] !== content) {
eventLoger(evnet, fullEnterPath);
cache[fullEnterPath] = content;
createStream(_objectSpread(_objectSpread({}, streamOptions), {}, {
patterns: fullEnterPath
}));
}
}
}); // used for node api shutdown monitoring
extSignals.forEach(signal => {
process.once(signal, () => watcher.close());
});
}
resolve();
});
});
}
/**
* @param {{ cwd: string; watch?: boolean; userConfig?: BuildConfig }} options - Node api startup parameters.
* @param {string} options.cwd - Root directory.
* @param {boolean} options.watch - Whether to enable monitoring.
* @param {BuildConfig} options.userConfig - User configuration
*/
function build(_x) {
return _build.apply(this, arguments);
}
function _build() {
_build = _asyncToGenerator(function* (options) {
let userConfig = getUserConfig(options.cwd);
if (userConfig && !Object.keys(userConfig).length) {
let rootConfigPath;
for (let i = 0; i < configFileNames.length; i++) {
rootConfigPath = yield (0, _findUp().default)(configFileNames[i]);
if (rootConfigPath) {
rootConfigPath = _path().default.join(rootConfigPath, '..');
break;
}
}
if (rootConfigPath) {
userConfig = getUserConfig(rootConfigPath);
delete userConfig.packages;
}
}
const config = _objectSpread(_objectSpread({}, defaultConfig), userConfig);
if (config.packages) {
const packagesPaths = config.packages.map(dir => _path().default.join(options.cwd, config.packageDirName, dir)).filter(dir => _fs().default.statSync(dir).isDirectory());
while (packagesPaths.length) {
const packagePath = packagesPaths.shift();
const packageConfig = getUserConfig(packagePath);
process.chdir(packagePath);
console.log(`${_chalk().default.blue(_figures().default.info, 'Package:')} ${_chalk().default.red(_path().default.basename(packagePath))}`);
yield compile({
cwd: options.cwd,
watch: !!options.watch,
currentDirPath: packagePath,
currentConfig: _objectSpread(_objectSpread({}, config), packageConfig)
});
}
} else {
yield compile({
watch: !!options.watch,
currentDirPath: options.cwd,
currentConfig: config,
cwd: options.cwd
});
}
});
return _build.apply(this, arguments);
}