Skip to content
This repository has been archived by the owner on Sep 9, 2021. It is now read-only.

Commit

Permalink
Merge pull request #1 from MicrosApp/develop
Browse files Browse the repository at this point in the history
Develop
  • Loading branch information
zyao89 committed Oct 8, 2019
2 parents 6e2689e + ac7c56a commit 0d7c9c9
Show file tree
Hide file tree
Showing 16 changed files with 645 additions and 23 deletions.
8 changes: 8 additions & 0 deletions bin/base.js
@@ -0,0 +1,8 @@
'use strict';

// 注册插件
const exportsBase = require('@micro-app/cli/bin/base');

// const { cmd, argv, service } = exportsBase;

module.exports = exportsBase;
10 changes: 10 additions & 0 deletions bin/micro-app-build.js
@@ -0,0 +1,10 @@
#!/usr/bin/env node
'use strict';

process.env.NODE_ENV = process.env.NODE_ENV || 'production';

const yParser = require('yargs-parser');
const argv = yParser(process.argv.slice(2));
const { service } = require('./base');

service.run('build', argv);
72 changes: 72 additions & 0 deletions micro-app.config.js
@@ -0,0 +1,72 @@
'use strict';

module.exports = {
name: '@micro-app/demo',
description: '',
version: '0.0.1',
type: '', // types 类型
webpack: { // webpack 配置 (只有自己使用)
// output: {
// path: path.resolve(__dirname, 'public'),
// publicPath: '/public/',
// },
},

entry: {
main: './test/index.js',
},

htmls: [
{
template: './test/index.js',
},
],

// staticPath: '',

// dlls: [
// {
// context: __dirname,
// },
// ],

alias: { // 前端
api: 'abc',
config: {
link: 'abc',
description: '配置',
},
service: {
link: 'abc',
description: '接口',
type: 'server',
},
},

strict: true,

// micros: [ 'test' ], // 被注册的容器
// micros$$test: { // 单独配置
// disabled: true, // 禁用入口
// link: '', // 本地路径, 进行本地开发使用的软链接.
// },

// 服务配置
server: {
entry: '', // 服务端入口
port: 8088, // 服务端口号
options: {
// 服务端回调参数
},
},

// plugins: [
// [{
// id: 'test',
// description: '这是test',
// link: __dirname + '/test/testPlugin',
// }, {
// a: 1,
// }],
// ],
};
15 changes: 11 additions & 4 deletions package.json
@@ -1,12 +1,17 @@
{
"name": "@micro-app/plugin-webpack-adapter",
"version": "0.0.5",
"version": "0.1.0-beta.1",
"description": "[Plugin] webpack adapter plugin.",
"main": "src/index.js",
"bin": {
"micro-app-build": "./bin/micro-app-build.js"
},
"scripts": {
"test": "jest"
},
"files": [
"bin",
"plugins",
"src"
],
"homepage": "https://github.com/MicrosApp/MicroApp-Plugin-Webpack-Adapter",
Expand All @@ -31,11 +36,12 @@
},
"license": "MIT",
"peerDependencies": {
"@micro-app/core": ">=0.1.5"
"@micro-app/core": ">=0.1.8",
"@micro-app/cli": ">=0.2.0"
},
"devDependencies": {
"@micro-app/cli": "^0.1.5",
"@micro-app/core": "^0.1.5",
"@micro-app/cli": "^0.2.0-beta.1",
"@micro-app/core": "^0.1.8",
"@types/jest": "^24.0.18",
"babel-eslint": "^10.0.3",
"coveralls": "^3.0.6",
Expand All @@ -44,6 +50,7 @@
"jest": "^24.9.0"
},
"dependencies": {
"cli-highlight": "^2.1.1",
"webpack-chain": "^6.0.0"
}
}
104 changes: 104 additions & 0 deletions plugins/commands/build/index.js
@@ -0,0 +1,104 @@
'use strict';

module.exports = function buildCommand(api, opts) {

const chalk = require('chalk');
const tryRequire = require('try-require');
const _ = require('lodash');

const registerMethods = require('./methods');

registerMethods(api);

// start
api.registerCommand('build', {
description: 'build for production',
usage: 'micro-app build [options]',
options: {
'--mode': 'specify env mode (default: development)',
'--type <type>': 'adapter type, eg. [ webpack, vusion ].',
'--progress': 'show how progress is reported during a compilation.',
},
details: `
Examples:
${chalk.gray('# vusion')}
micro-app build --type vusion
`.trim(),
}, args => {
process.env.NODE_ENV = process.env.NODE_ENV || 'production';

return runBuild(api, args);
});

function runBuild(api, args) {
const logger = api.logger;

api.applyPluginHooks('beforeBuild', { args });

let _webpackConfig = api.resolveWebpackConfig();

const { webpackConfig } = api.applyPluginHooks('modifyWebpackConfig', {
args,
webpackConfig: _webpackConfig,
});

if (
!_.isPlainObject(webpackConfig) || !webpackConfig
) {
logger.error('[Plugin] modifyWebpackConfig must return { args, webpackConfig }');
return process.exit(1);
}

// 更新一次
api.setState('webpackConfig', webpackConfig);
_webpackConfig = _.cloneDeep(webpackConfig);

const webpack = require('webpack');

const compiler = webpack(webpackConfig);

const progress = args.progress || false;

if (progress && webpack && webpack.ProgressPlugin) {
try {
require('../../../src/webpackPlugins/ProgressPlugin')(api, compiler);
} catch (error) {
logger.warn(error);
}
}

return new Promise((resolve, reject) => {
const spinner = logger.spinner('Building for production...');
spinner.start();
compiler.run((err, stats) => {
spinner.stop();
if (err) {
// 在这里处理错误
api.applyPluginHooks('onBuildFail', { err, args });
}

api.applyPluginHooks('afterBuild', { args });

if (err) {
return reject(err);
}

process.stdout.write(stats.toString(Object.assign({
colors: true,
modules: false,
children: false,
chunks: false,
chunkModules: false,
}, webpackConfig.stats || {})) + '\n');

api.applyPluginHooks('onBuildSuccess', { args });
// 处理完成
resolve();
});
}).then(() => {
api.logger.success('>>> Build Success >>>');
}).catch(e => {
api.logger.error('>>> Build Error >>>', e);
});
}
};
27 changes: 27 additions & 0 deletions plugins/commands/build/methods.js
@@ -0,0 +1,27 @@
'use strict';

module.exports = api => {

api.registerMethod('modifyWebpackConfig', {
type: api.API_TYPE.MODIFY,
description: '对服务启动前对 webpack config 进行修改, 需要返回所有参数',
});

api.registerMethod('onBuildSuccess', {
type: api.API_TYPE.EVENT,
description: '构建成功时事件',
});
api.registerMethod('onBuildFail', {
type: api.API_TYPE.EVENT,
description: '构建失败时事件',
});
api.registerMethod('beforeBuild', {
type: api.API_TYPE.EVENT,
description: '开始构建前事件',
});
api.registerMethod('afterBuild', {
type: api.API_TYPE.EVENT,
description: '构建结束后事件',
});

};
107 changes: 107 additions & 0 deletions plugins/commands/inspect/index.js
@@ -0,0 +1,107 @@
'use strict';
module.exports = function inspectCommand(api, opts) {

const chalk = require('chalk');
const _ = require('lodash');

const logger = api.logger;

api.registerCommand('inspect', {
description: 'inspect internal webpack config',
usage: 'micro-app inspect [options] [...paths]',
options: {
'--mode': 'specify env mode (default: development)',
'--rule <ruleName>': 'inspect a specific module rule',
'--plugin <pluginName>': 'inspect a specific plugin',
'--rules': 'list all module rule names',
'--plugins': 'list all plugin names',
'--verbose': 'show full function definitions in output',
'--type <type>': 'adapter type, eg. [ webpack, vusion, etc. ].',
'--open-soft-link': '启用开发软链接',
'--open-disabled-entry': '支持可配置禁用部分模块入口.',
},
details: `
Examples:
${chalk.gray('# vusion')}
micro-app inspect --type vusion
${chalk.gray('# open soft link')}
micro-app inspect --type vusion --open-soft-link
`.trim(),
},
args => {
const { toString } = require('webpack-chain');
const { highlight } = require('cli-highlight');

const { _: paths, verbose } = args;

let config = api.resolveWebpackConfig();

const { webpackConfig } = api.applyPluginHooks('modifyWebpackConfig', {
args,
webpackConfig: config,
});

if (
!_.isPlainObject(webpackConfig) || !webpackConfig
) {
logger.error('[Plugin] modifyWebpackConfig must return { args, webpackConfig }');
return process.exit(1);
}

// 更新一次
api.setState('webpackConfig', webpackConfig);
config = _.cloneDeep(webpackConfig);

let res;
let hasUnnamedRule;
if (args.rule) {
res = config.module.rules.find(r => r.__ruleNames[0] === args.rule);
} else if (args.plugin) {
res = Array.isArray(config.plugins)
? config.plugins.find(p => p.__pluginName === args.plugin)
: {};
} else if (args.rules) {
res = config.module && Array.isArray(config.module.rules)
? config.module.rules.map(r => {
const name = r.__ruleNames ? r.__ruleNames[0] : 'Nameless Rule (*)';

hasUnnamedRule = hasUnnamedRule || !r.__ruleNames;

return name;
})
: [];
} else if (args.plugins) {
res = Array.isArray(config.plugins)
? config.plugins.map(p => p.__pluginName || p.constructor.name)
: [];
} else if (paths.length > 1) {
res = {};
paths.forEach(path => {
res[path] = _.get(config, path);
});
} else if (paths.length === 1) {
res = _.get(config, paths[0]);
} else {
res = config;
}

const output = toString(res, { verbose });
logger.logo(highlight(output, { language: 'js' }));

// Log explanation for Nameless Rules
if (hasUnnamedRule) {
logger.logo(`--- ${chalk.green('Footnotes')} ---`);
logger.logo(`*: ${chalk.green(
'Nameless Rules'
)} were added through the ${chalk.green(
'configureWebpack()'
)} API (possibly by a plugin) instead of ${chalk.green(
'chainWebpack()'
)} (recommended).
You can run ${chalk.green(
'micro-app inspect'
)} without any arguments to inspect the full config and read these rules' config.`);
}
}
);
};

0 comments on commit 0d7c9c9

Please sign in to comment.