Skip to content

Commit

Permalink
feat: add component build
Browse files Browse the repository at this point in the history
  • Loading branch information
GGwujun committed Aug 10, 2021
1 parent 95a9619 commit f984918
Show file tree
Hide file tree
Showing 13 changed files with 274 additions and 37 deletions.
1 change: 0 additions & 1 deletion .yarnrc
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# Using the official mirror source
registry "https://registry.yarnpkg.com"
node-sass:registry "https://registry.npm.taobao.org/"
sass_binary_site "https://npm.taobao.org/mirrors/node-sass/"
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ export function fixRoutePathInWindows(path?: string) {
return path.replace(/:/g, '.');
}

export default function (api: IApi) {
export default function(api: IApi) {
class HtmlWebpackPlugin {
apply(compiler: webpack.Compiler) {
compiler.hooks.emit.tapPromise(
Expand Down Expand Up @@ -58,6 +58,7 @@ export default function (api: IApi) {
const enableWriteToDisk =
api.config.devServer && api.config.devServer.writeToDisk;
if (
!api.args.component &&
!mfsu &&
(env === 'production' || enableWriteToDisk) &&
id === 'webpack' &&
Expand Down
18 changes: 12 additions & 6 deletions packages/preset-built-in/src/plugins/commands/build/build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import generateFiles from '../generateFiles';

const logger = new Logger('vmi:preset-build-in');

export default function (api: IApi) {
export default function(api: IApi) {
const {
paths,
utils: { rimraf },
Expand All @@ -20,17 +20,23 @@ export default function (api: IApi) {
api.registerCommand({
name: 'build',
description: 'build application for production',
fn: async function () {
fn: async function() {
cleanTmpPathExceptCache({
absTmpPath: paths.absTmpPath!,
});

// generate files
await generateFiles({ api, watch: false });
// build component not generate files
if (!api.args.component) {
// generate files
await generateFiles({ api, watch: false });
}

// build
const { bundler, bundleConfigs, bundleImplementor } =
await getBundleAndConfigs({ api });
const {
bundler,
bundleConfigs,
bundleImplementor,
} = await getBundleAndConfigs({ api });
try {
// clear output path before exec build
if (process.env.CLEAR_OUTPUT !== 'none') {
Expand Down
3 changes: 1 addition & 2 deletions packages/preset-built-vmi/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
export { IDumiOpts } from './context';

export default function () {
export default function() {
return {
plugins: [
require.resolve('./plugins/features/init'),
Expand All @@ -16,7 +16,6 @@ export default function () {
require.resolve('./plugins/features/webpack'),
require.resolve('./plugins/features/outputPath'),
require.resolve('./plugins/features/alias'),
// require.resolve('./plugins/features/component'),
],
};
}
8 changes: 5 additions & 3 deletions packages/preset-built-vmi/src/plugins/features/webpack.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,15 +14,17 @@ export default (api: IApi) => {
},
});

api.chainWebpack(async (memo) => {
const client = require.resolve('@winfe/client/package.json');
api.chainWebpack(async memo => {
memo.resolve.extensions.merge(['.vue']);

// vue-loader
memo.module
.rule('vue')
.test(/\.vue$/i)
.include.add([
cwd,
// client none compile, need add include
dirname(client),
dirname(require.resolve('@winfe/client/package.json')),
// import module out of cwd using APP_ROOT
// issue: https://github.com/umijs/umi/issues/5594
...(process.env.APP_ROOT ? [process.cwd()] : []),
Expand Down
2 changes: 2 additions & 0 deletions packages/vmi/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,8 @@
"@winfe/preset-built-in": "^1.0.6",
"@winfe/preset-built-vmi": "^1.0.6",
"@winfe/runtime": "^1.0.6",
"minio": "^7.0.18",
"string-width": "^5.0.0",
"v8-compile-cache": "2.3.0"
},
"bin": {
Expand Down
4 changes: 4 additions & 0 deletions packages/vmi/src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,8 +72,11 @@ if (process.title === 'node') {
break;
default:
const name = args._[0];
const plugins = [];
if (name === 'build') {
process.env.NODE_ENV = 'production';
if (args.component)
plugins.push(require.resolve('./plugins/component'));
}

// Init webpack version determination and require hook for build command
Expand All @@ -83,6 +86,7 @@ if (process.title === 'node') {
cwd: getCwd(),
pkg: getPkg(process.cwd()),
configFiles: DEFAULT_CONFIG_FILES,
plugins,
}).run({
name,
args,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { IApi } from '@umijs/types';
import { resolve } from 'path';
import uploadMaterialOutput from '../uploadMaterialOutput';

const externals = {
vue: {
Expand All @@ -9,11 +10,17 @@ const externals = {
amd: 'vue',
},
'element-ui': {
root: 'element-ui',
root: 'elementUi',
commonjs: 'element-ui',
commonjs2: 'element-ui',
amd: 'element-ui',
},
'@winfe/win-request': {
root: 'winRequest',
commonjs: 'win-request',
commonjs2: 'win-request',
amd: 'win-request',
},
};

export default (api: IApi) => {
Expand All @@ -29,15 +36,14 @@ export default (api: IApi) => {
},
});

api.chainWebpack(async (memo) => {
memo.entryPoints.delete('umi');
memo.entryPoints.delete('vmi');
api.chainWebpack(async memo => {
memo.entryPoints.clear();
memo.entry('index').add(resolve(cwd, './index.js'));

// component output need umd
memo.output
.publicPath('./')
.path(resolve(cwd, './lib/'))
.path(resolve(cwd, `dist/${require(`${cwd}/package.json`).version}`))
.filename('index.js')
.chunkFilename('[id].js')
.libraryTarget('umd');
Expand All @@ -47,7 +53,7 @@ export default (api: IApi) => {
// 添加全局scss文件
const types = ['vue-modules', 'vue', 'normal-modules', 'normal'];

types.forEach((type) => {
types.forEach(type => {
//匹配到所有需要导入的文件
memo.module
.rule('sass')
Expand All @@ -59,17 +65,22 @@ export default (api: IApi) => {
});
});

memo.module
.rule('css')
.use('extract-css-loader')
.tap((options) => {
// 修改它的选项...
options.filename = 'index.css';
return options;
});
memo
.plugin('extract-css')
.tap(options =>
options.map(option => ({ ...option, filename: 'index.css' })),
);

memo.plugin('CleanWebpackPlugin').use(require('clean-webpack-plugin').CleanWebpackPlugin);
memo
.plugin('CleanWebpackPlugin')
.use(require('clean-webpack-plugin').CleanWebpackPlugin);

return memo;
});

api.onBuildComplete(({ err }) => {
if (!err) {
if (api.args.upload) uploadMaterialOutput(cwd);
}
});
};
1 change: 0 additions & 1 deletion packages/vmi/src/plugins/fixtures/normal/.gitkeep

This file was deleted.

59 changes: 59 additions & 0 deletions packages/vmi/src/uploadMaterialOutput.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import path from 'path';
import chalk from 'chalk';
import fs from 'fs';
import title from './utils/printTitle';

const Minio = require('minio');

export default async (cwd: string) => {
const minioClient = new Minio.Client({
endPoint: '172.16.6.51',
port: 9000,
useSSL: false,
accessKey: 'www.winning.com.cn',
secretKey: 'www.winning.com.cn',
});
const pkg = require(`${cwd}/package.json`);

const metaData = {
'Content-Type': 'application/octet-stream',
'X-Amz-Meta-Testing': 1234,
example: 5678,
};

// 递归上传dist下对应当前版本的所有打包产物到minio
const domainName = pkg.name.split('/')[1].split('-')[0];
const filepath = `materials-umd-lib/${domainName}/${pkg.name}/${pkg.version}/`;
const fileDir = `${cwd}/dist/${pkg.version}/`;

const classifyFiles = (filepath: string, dir: string) => {
fs.readdir(dir, (err, files) => {
files.forEach(filename => {
let filedir = path.join(dir, filename);
fs.stat(filedir, (err, stats) => {
if (!err) {
let isFile = stats.isFile(); //是文件
if (isFile) {
upload(`${filepath}${filename}`, `${dir}${filename}`);
} else {
classifyFiles(`${filepath}${filename}/`, `${dir}${filename}/`);
}
}
});
});
});
};
// 上传方法
const upload = (filepath: string, files: string) => {
minioClient.fPutObject('winex', filepath, files, metaData, function(
err: any,
) {
if (err) {
console.log(chalk.red('upload fail', err));
}
});
};

classifyFiles(filepath, fileDir);
title('success', 'UPLOAD', 'Uploaded successfully ');
};
3 changes: 0 additions & 3 deletions packages/vmi/src/utils/fixtures/normal/package.json

This file was deleted.

64 changes: 64 additions & 0 deletions packages/vmi/src/utils/printTitle.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
import chalk from 'chalk';

function capitalizeFirstLetter(string: string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}

function textColor(severity: string) {
switch (severity.toLowerCase()) {
case 'success':
return 'green';
case 'info':
return 'blue';
case 'note':
return 'white';
case 'warning':
return 'yellow';
case 'error':
return 'red';
default:
return 'red';
}
}

function bgColor(severity: string) {
const color = textColor(severity);
return 'bg' + capitalizeFirstLetter(color);
}

function formatTitle(severity: string, message: string) {
return chalk[bgColor(severity)].black('', message, '');
}

function formatText(severity: string, message: string) {
return chalk[textColor(severity)](message);
}

export default function title(
severity: string,
title: string,
subtitle: string,
) {
const date = new Date();
const dateString = chalk.grey(date.toLocaleTimeString());
const titleFormatted = formatTitle(severity, title);
const subTitleFormatted = formatText(severity, subtitle);
const message = `${titleFormatted} ${subTitleFormatted}`;

// In test environment we don't include timestamp
if (process.env.NODE_ENV === 'test') {
console.log(message);
console.log();
return;
}

// // Make timestamp appear at the end of the line
// let logSpace =
// // process.stdout.columns - stringWidth(message) - stringWidth(dateString);
// if (logSpace <= 0) {
// logSpace = 10;
// }

console.log(`${message}${dateString}`);
console.log();
}
Loading

0 comments on commit f984918

Please sign in to comment.