Skip to content

Commit 4533d9f

Browse files
committed
🎨 整体重构 build 和 serve 等
1 parent eaab279 commit 4533d9f

File tree

22 files changed

+396
-7985
lines changed

22 files changed

+396
-7985
lines changed

README.md

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -85,8 +85,6 @@ npx micro-app show methods
8585
```js
8686
╰─➤ npx micro-app show methods
8787
Plugin Methods:
88-
* beforeMergeWebpackConfig ( 合并 webpack 配置之前事件 )
89-
* afterMergeWebpackConfig ( 合并 webpack 配置之后事件 )
9088
* modifyChainWebpcakConfig ( 合并之后提供 webpack-chain 进行再次修改事件 )
9189
* onChainWebpcakConfig ( 修改之后提供 webpack-chain 进行查看事件 )
9290
* modifyWebpackConfig ( 合并之后提供 webpack config 进行再次修改事件 )

package.json

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -44,12 +44,10 @@
4444
]
4545
},
4646
"peerDependencies": {
47-
"@micro-app/cli": ">=0.3.0",
48-
"@micro-app/core": ">=0.3.0"
47+
"@micro-app/cli": ">=0.3.0"
4948
},
5049
"devDependencies": {
51-
"@micro-app/cli": "^0.3.0-alpha.1",
52-
"@micro-app/core": "^0.3.0-alpha.3",
50+
"@micro-app/cli": "file:../MicroApp-CLI",
5351
"@types/jest": "^24.0.19",
5452
"babel-eslint": "^10.0.3",
5553
"coveralls": "^3.0.7",
@@ -58,17 +56,17 @@
5856
"husky": "^3.0.9",
5957
"jest": "^24.9.0",
6058
"lint-staged": "^9.4.2",
61-
"webpack": "^4.41.1"
59+
"webpack": "^4.41.1",
60+
"webpack-dev-server": "^3.9.0"
6261
},
6362
"dependencies": {
64-
"@micro-app/shared-utils": "^0.1.7",
63+
"@micro-app/shared-utils": "^0.1.8",
6564
"address": "^1.1.2",
6665
"cli-highlight": "^2.1.4",
6766
"clipboardy": "^2.1.0",
6867
"default-gateway": "^5.0.5",
6968
"launch-editor-middleware": "^2.2.1",
7069
"portfinder": "^1.0.25",
71-
"webpack-chain": "^6.0.0",
72-
"webpack-merge": "^4.2.2"
70+
"webpack-chain": "^6.0.0"
7371
}
7472
}

src/commands/build/build.test.js

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,8 @@ describe('Command build', () => {
1212

1313
it('build run', async () => {
1414

15+
process.env.NODE_ENV = 'production';
16+
1517
const { service } = require('@micro-app/cli');
1618

1719
await service.run('build', getArgvs());
@@ -24,6 +26,8 @@ describe('Command build', () => {
2426

2527
it('global cmd config', async () => {
2628

29+
process.env.NODE_ENV = 'production';
30+
2731
const { service } = require('@micro-app/cli');
2832

2933
const result = await service.run('build', Object.assign({

src/commands/build/index.js

Lines changed: 15 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -26,26 +26,33 @@ module.exports = function buildCommand(api, opts) {
2626
usage: 'micro-app build [options]',
2727
options: {
2828
'--mode': 'specify env mode (default: development)',
29-
'--type <type>': 'adapter type, eg. [ webpack, vusion ].',
29+
'--type <type>': 'adapter type, eg. [ webpack, etc. ].',
3030
'--dest': 'specify output directory',
3131
'--watch': 'watch for changes',
3232
'--clean': 'remove the dist directory before building the project',
33-
'--target': `app | lib (default: ${defaults.target})`,
33+
// '--target': `app | lib (default: ${defaults.target})`,
3434
},
3535
details: `
3636
Examples:
37-
${chalk.gray('# vusion')}
38-
micro-app build --type vusion
37+
${chalk.gray('# watch')}
38+
micro-app build --watch
3939
`.trim(),
4040
}, async args => {
41+
const logger = api.logger;
42+
43+
// TODO 兼容, 下个版本删除
44+
if (args.t && !args.type) {
45+
args.type = args.t;
46+
logger.warn('you should be use "--type <type>"!!!');
47+
}
48+
4149
for (const key in defaults) {
4250
if (args[key] == null) {
4351
args[key] = defaults[key];
4452
}
4553
}
4654

4755
const mode = api.mode;
48-
const logger = api.logger;
4956

5057
const webpack = tryRequire('webpack');
5158
if (!webpack) {
@@ -84,8 +91,7 @@ Examples:
8491
webpack(webpackConfig, (err, stats) => {
8592

8693
api.applyPluginHooks('afterBuild', { args });
87-
88-
spinner.stop();
94+
spinner.info('Build Done');
8995

9096
if (err) {
9197
// 在这里处理错误
@@ -94,6 +100,8 @@ Examples:
94100
}
95101

96102
if (stats.hasErrors()) {
103+
// 在这里处理错误
104+
api.applyPluginHooks('onBuildFail', { stats, args });
97105
return reject('Build failed with errors.');
98106
}
99107

src/commands/inspect/index.js

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -11,21 +11,19 @@ module.exports = function inspectCommand(api, opts) {
1111
usage: 'micro-app inspect [options] [...paths]',
1212
options: {
1313
'--mode': 'specify env mode (default: development)',
14+
'--type <type>': 'adapter type, eg. [ webpack, etc. ].',
1415
'--rule <ruleName>': 'inspect a specific module rule',
1516
'--plugin <pluginName>': 'inspect a specific plugin',
1617
'--rules': 'list all module rule names',
1718
'--plugins': 'list all plugin names',
1819
'--verbose': 'show full function definitions in output',
19-
'--type <type>': 'adapter type, eg. [ webpack, vusion, etc. ].',
20-
'--open-soft-link': '启用开发软链接',
21-
'--open-disabled-entry': '支持可配置禁用部分模块入口.',
2220
},
2321
details: `
2422
Examples:
25-
${chalk.gray('# vusion')}
26-
micro-app inspect --type vusion
27-
${chalk.gray('# open soft link')}
28-
micro-app inspect --type vusion --open-soft-link
23+
${chalk.gray('# mode: development')}
24+
micro-app inspect --mode development
25+
${chalk.gray('# inspect all plugins')}
26+
micro-app inspect --plugins
2927
`.trim(),
3028
},
3129
args => {

src/commands/serve/index.js

Lines changed: 55 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -15,15 +15,14 @@ module.exports = function serveCommand(api, opts) {
1515

1616
api.modifyCreateDevServer(() => {
1717

18-
const { _, tryRequire, chalk, openBrowser, Env } = require('@micro-app/shared-utils');
19-
const path = require('path');
18+
const { _, tryRequire, chalk, openBrowser, Env, semver } = require('@micro-app/shared-utils');
2019
const url = require('url');
21-
const launchEditorMiddleware = require('launch-editor-middleware ');
20+
const launchEditorMiddleware = require('launch-editor-middleware');
2221
const portfinder = require('portfinder');
23-
const prepareURLs = require('../../../utils/prepareURLs');
24-
const prepareProxy = require('../../../utils/prepareProxy');
25-
const validateWebpackConfig = require('../../../utils/validateWebpackConfig');
26-
const isAbsoluteUrl = require('../../../utils/isAbsoluteUrl');
22+
const prepareURLs = require('../../utils/prepareURLs');
23+
const prepareProxy = require('../../utils/prepareProxy');
24+
const validateWebpackConfig = require('../../utils/validateWebpackConfig');
25+
const isAbsoluteUrl = require('../../utils/isAbsoluteUrl');
2726

2827
function addConfig(id, fn) {
2928
if (tryRequire.resolve(id)) {
@@ -44,13 +43,22 @@ module.exports = function serveCommand(api, opts) {
4443
logger.throw('[serve]', 'Not Found "webpack-dev-server"!');
4544
}
4645

46+
const webpackVersion = require('webpack/package.json').version;
47+
const webpackDevServerVersion = require('webpack-dev-server/package.json').version;
48+
4749
const isInContainer = checkInContainer();
4850
const isProduction = mode === 'production';
4951

5052
const options = api.config || {};
5153

54+
const spinner = logger.spinner(`Starting for ${mode}...`);
55+
5256
// configs that only matters for dev server
5357
api.modifyChainWebpcakConfig(webpackChain => {
58+
59+
// webpack 4
60+
const isWebpack4 = semver.satisfies(webpackVersion, '>=4');
61+
5462
if (mode !== 'production' && mode !== 'test') {
5563
webpackChain
5664
.devtool('cheap-module-eval-source-map');
@@ -61,20 +69,40 @@ module.exports = function serveCommand(api, opts) {
6169
.use(require(id));
6270
});
6371

64-
// https://github.com/webpack/webpack/issues/6642
65-
// https://github.com/vuejs/vue-cli/issues/3539
66-
webpackChain
67-
.output
68-
.globalObject('(typeof self !== \'undefined\' ? self : this)');
72+
if (isWebpack4) {
73+
// https://github.com/webpack/webpack/issues/6642
74+
// https://github.com/vuejs/vue-cli/issues/3539
75+
webpackChain
76+
.output
77+
.globalObject('(typeof self !== \'undefined\' ? self : this)');
78+
}
6979

7080
if (options.devServer && options.devServer.progress !== false) {
7181
addConfig('webpack/lib/ProgressPlugin', id => {
7282
webpackChain
7383
.plugin('progress')
74-
.use(require(id));
84+
.use(require(id), [
85+
{
86+
modules: false,
87+
profile: false,
88+
handler: (percentage, message /* , ...args */) => {
89+
if (spinner && percentage <= 0) {
90+
spinner.start();
91+
}
92+
if (spinner) {
93+
spinner.text = Number(percentage * 100).toFixed(2) + '% ' + chalk.gray(`( ${message} )`);
94+
}
95+
// api.logger.logo(percentage, message, ...args);
96+
if (spinner && percentage >= 1) {
97+
spinner.succeed('Compiled Done!');
98+
}
99+
},
100+
},
101+
]);
75102
});
76103
}
77104
}
105+
return webpackChain;
78106
});
79107

80108
const webpackConfig = api.resolveWebpackConfig();
@@ -88,7 +116,7 @@ module.exports = function serveCommand(api, opts) {
88116
// in webpack config
89117
const projectDevServerOptions = Object.assign(
90118
webpackConfig.devServer || {},
91-
options.devServer
119+
options.devServer || {}
92120
);
93121

94122
// entry arg
@@ -125,7 +153,7 @@ module.exports = function serveCommand(api, opts) {
125153

126154
const proxySettings = prepareProxy(
127155
projectDevServerOptions.proxy,
128-
api.resolve('public')
156+
options.staticPaths || []
129157
);
130158

131159
// inject dev & hot-reload middleware entries
@@ -164,20 +192,24 @@ module.exports = function serveCommand(api, opts) {
164192
// create compiler
165193
const compiler = webpack(webpackConfig);
166194

195+
const isWebpackDevServer3 = semver.satisfies(webpackDevServerVersion, '>=3');
196+
167197
// create server
168-
const server = new WebpackDevServer(compiler, Object.assign({
198+
const server = new WebpackDevServer(compiler, Object.assign(isWebpackDevServer3 ? {
169199
logLevel: 'silent',
200+
} : {}, {
170201
clientLogLevel: 'silent',
171202
historyApiFallback: {
172203
disableDotRule: true,
173204
rewrites: genHistoryApiFallbackRewrites(options.publicPath, options.pages),
174205
},
175-
contentBase: api.resolve('public'),
206+
contentBase: options.staticPaths || [],
176207
watchContentBase: !isProduction,
177208
hot: !isProduction,
178209
compress: isProduction,
179210
publicPath: options.publicPath,
180-
overlay: isProduction // TODO disable this
211+
// TODO disable this
212+
overlay: isProduction
181213
? false
182214
: { warnings: false, errors: true },
183215
}, projectDevServerOptions, {
@@ -210,21 +242,23 @@ module.exports = function serveCommand(api, opts) {
210242
}));
211243

212244
[ 'SIGINT', 'SIGTERM' ].forEach(signal => {
213-
process.on(signal, () => {
245+
process.once(signal, () => {
214246
server.close(() => {
215247
process.exit(0);
216248
});
217249
});
218250
});
219251

220-
const spinner = logger.spinner(`Starting for ${mode}...`);
221-
222252
return new Promise((resolve, reject) => {
223253
spinner.start();
224254

225255
// log instructions & open browser on first compilation complete
226256
let isFirstCompile = true;
227257
const done = stats => {
258+
if (isFirstCompile) {
259+
spinner.stop();
260+
}
261+
228262
if (stats.hasErrors()) {
229263
return;
230264
}

0 commit comments

Comments
 (0)