antd-tools 工具分析

ant-design 通过 npm install 安装后,antd 目录下面有一个 dist 目录,lib 目录和一个 package.json 文件。package.json 中的 main 对应文件 lib/index.js。

  1. antd
  2. |----- dist
  3. +------ antd.js
  4. |------ antd.css
  5. |------ antd.less
  6. |------ antd.min.css
  7. |------ antd.min.js
  8. |------ ......
  9. |----- lib
  10. +------ alert
  11. +------ affix
  12. +------ anchor
  13. +------ card
  14. +------ ......

dist, lib 目录分别使用 npm run dist, npm run compile 生成。而这两个命令最终都是调用的 antd-tools , 因此有必须要先了解下 antd-tools 这个工具。但是 github.com 上关于这个包,只有源代码,因此,我们就从源码的层面分析下它。

antd-tools 源码分析

antd-tools 中的 bin 属性内容如下:

  1. "bin": {
  2. "antd-tools": "./bin/antd-tools.js",
  3. "antd-tools-run": "./bin/antd-tools-run.js"
  4. },

antd-tools 对应的文件内容如下:

  1. #!/usr/bin/env node
  2. require('../lib/cli/');

下面看看 lib/cli/index.js 文件的内容:

  1. #!/usr/bin/env node
  2. 'use strict';
  3. require('colorful').colorful();
  4. const program = require('commander');
  5. const packageInfo = require('../../package.json');
  6. program
  7. .version(packageInfo.version)
  8. .command('run [name]', 'run specified task')
  9. .parse(process.argv);
  10. // https://github.com/tj/commander.js/pull/260
  11. const proc = program.runningCommand;
  12. if (proc) {
  13. proc.on('close', process.exit.bind(process));
  14. proc.on('error', () => {
  15. process.exit(1);
  16. });
  17. }
  18. const subCmd = program.args[0];
  19. if (!subCmd || subCmd !== 'run') {
  20. program.help();
  21. }

上面代码比较简单,使用tj大神的commander.js工具,关键在于parse方法上。该方法解析argv, 设置options, 如果有定义命令,则调用它。

对于 antd 的 npm run dist 命令和 npm run compile命 令来说,就是 antd-tools run dist, antd-tools run compile。最终执行子命令 antd-tools/bin/antd-tools-run.js。
真正的子命令代码位于 antd-tools/lib/cli/run.js。

  1. #!/usr/bin/env node
  2. 'use strict';
  3. require('colorful').colorful();
  4. const gulp = require('gulp');
  5. const program = require('commander');
  6. program.on('--help', () => {
  7. console.log(' Usage:'.to.bold.blue.color);
  8. console.log();
  9. });
  10. program.parse(process.argv);
  11. const task = program.args[0];
  12. if (!task) {
  13. program.help();
  14. } else {
  15. console.log('antd-tools run', task);
  16. require('../gulpfile');
  17. gulp.start(task);
  18. }
  19. // 这里就是调用该脚本,task分别为dist, compile。

npm run dist 分析

该命令就是调用 atool-build 构建 antd 源码。 将源码构建到dist目录。

  1. gulp.task('dist', (done) => {
  2. dist(done);
  3. });
  4. function dist(done) {
  5. execSync('rimraf dist');
  6. process.env.RUN_ENV = 'PRODUCTION';
  7. runCmd('atool-build', ['--devtool=#sourcemap'], (code) => {
  8. done(code);
  9. });

npm run compile 分析

将源码转换为 ES5 到 lib 文件夹中。JS源码是 TypeScript 实现的, css 使用 less 实现。
除了样式、js外,还有 svg, png 之类的。

除了npm run compile, 还有 npm run pub 用于发布编译后的代码的。

了解到这个层面,基本上可以对 antd源码中的组件进行分析和改装了。

antd 中组件位于 components 目录, 而相关的 typescript 定义相关的东西放在 typings 里边。

参考连接
http://ant-tool.github.io/atool-build.html
https://github.com/liangklfangl/atool-build-source