Guest User

Untitled

a guest
Nov 21st, 2017
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 6.55 KB | None | 0 0
  1. # Angular套件打包
  2.  
  3. 1.建立一個Angular NPM專案
  4. ```powershell
  5. ng new
  6. ```
  7.  
  8. 2.安裝打包所需NPM套件
  9. ```powershell
  10. npm install --save-dev child_process gulp gulp-base64 gulp-copy gulp-inline-ng2-template gulp-clean-css gulp-sass gulp-sourcemaps rimraf run-sequence
  11. ```
  12.  
  13. 3.建立`gulpfile.js`,**請記得編輯這個檔案的`modulePath`到自己的Module目錄**
  14. ```javascript
  15. var gulp = require('gulp'),
  16. gulp_sass = require('gulp-sass'),
  17. gulp_cleanCSS = require('gulp-clean-css'),
  18. gulp_sourceMaps = require('gulp-sourcemaps'),
  19. gulp_ngInlineTemplate = require('gulp-inline-ng2-template'),
  20. gulp_base64 = require('gulp-base64'),
  21. gulp_copy = require('gulp-copy'),
  22. runSequence = require('run-sequence'),
  23. fs = require('fs'),
  24. exec = require('child_process').exec,
  25. angularConfig = require('./.angular-cli.json'),
  26. path = require('path'),
  27. os = require('os');
  28.  
  29. // 這裡是這個LIB要匯出的模組路徑
  30. var modulePath = './src/app/shared';
  31.  
  32. console.log('Angular Module 編譯');
  33. console.log('====================');
  34. console.log(`匯出模組目錄: ${modulePath}`);
  35. console.time('time');
  36. /**
  37. * 取得Shell檔案路徑在各平台的表示
  38. * @param {String} path 路徑
  39. */
  40. function platformPath(path) {
  41. return /^win/.test(os.platform()) ? `${path}.cmd` : path;
  42. }
  43.  
  44. // #region 清除相關
  45. // 清除過去輸出目錄
  46. gulp.task('clean-dist', function(done) {
  47. exec('rimraf ./dist ./tmp_dist', function(err, stdOut, stdErr) {
  48. if (err) {
  49. done(err);
  50. } else {
  51. done();
  52. }
  53. });
  54. });
  55.  
  56. gulp.task('clean-index', function(done) {
  57. exec(`rimraf ${modulePath}/**/index.ts`, function(err, stdOut, stdErr) {
  58. if (err) {
  59. done(err);
  60. } else {
  61. done();
  62. }
  63. });
  64. });
  65.  
  66. gulp.task('clean-tmp', function(done) {
  67. exec(`rimraf ./tmp_source ./tmp_dist`, function(err, stdOut, stdErr) {
  68. if (err) {
  69. done(err);
  70. } else {
  71. done();
  72. }
  73. });
  74. });
  75. // #endregion
  76.  
  77. /**
  78. * 主要編譯過程
  79. */
  80. gulp.task('build', function(done) {
  81. runSequence(
  82. 'backup-source',
  83. 'compile-sass',
  84. 'assets-base64',
  85. 'clean-css',
  86. 'create-index',
  87. 'compile',
  88. 'export',
  89. 'clean-tmp',
  90. 'clean-index',
  91. function() {
  92. console.timeEnd('time');
  93. console.log('編譯結束, 編譯結果於 ./dist 目錄中, 如要發行則執行 npm publish dist');
  94. }
  95. );
  96. });
  97.  
  98. // NGC編譯
  99. gulp.task('compile', ['angular-inline', 'clean-dist'], function(done) {
  100. var executable = path.join(__dirname, platformPath('/node_modules/.bin/ngc'));
  101. exec(`${executable} -p ./tsconfig.json`, e => {
  102. fs.rename('dist', 'tmp_dist', function(err) {
  103. if (err) {
  104. throw err;
  105. }
  106. done();
  107. });
  108. });
  109. });
  110.  
  111. // 將HTML與CSS樣板轉換於TS檔案修飾器內
  112. gulp.task('angular-inline', function() {
  113. return gulp
  114. .src('./src/**/*.ts')
  115. .pipe(gulp_ngInlineTemplate({ base: '/src', useRelativePaths: true }))
  116. .pipe(gulp.dest('./src'));
  117. });
  118.  
  119. // 產生索引檔
  120. gulp.task('create-index', ['clean-index'], function(done) {
  121. function createIndex(path) {
  122. var files = fs.readdirSync(path);
  123. var index = '';
  124. files.forEach(file => {
  125. var stats = fs.statSync(path + '/' + file);
  126. var name = file;
  127. if (stats.isDirectory()) {
  128. createIndex(path + '/' + file);
  129. } else {
  130. if (
  131. !/\.ts$/gi.test(name) ||
  132. /\.spec\.ts$/gi.test(name) ||
  133. /\.test\.ts$/gi.test(name) ||
  134. /^index\.ts$/gi.test(name)
  135. ) {
  136. return;
  137. }
  138. name = name.replace(/\.ts$/g, '');
  139. if (name === 'index') return;
  140. }
  141.  
  142. index += `export * from \'./${name}\';\r\n`;
  143. });
  144. fs.writeFileSync(path + '/index.ts', index);
  145. }
  146.  
  147. createIndex(modulePath);
  148. done();
  149. });
  150.  
  151. // 將CSS中引用的圖片檔案BASE64寫到CSS檔案
  152. gulp.task('assets-base64', function() {
  153. return gulp
  154. .src('src/**/*.css')
  155. .pipe(
  156. gulp_base64({
  157. baseDir: './src',
  158. extensions: ['png', 'jpg', 'gif', 'ttf', 'woff', 'eot', 'svg'],
  159. maxImageSize: 200 * 1024,
  160. debug: false
  161. })
  162. )
  163. .pipe(
  164. gulp.dest(function(file) {
  165. return file.base;
  166. })
  167. );
  168. });
  169.  
  170. // 備份原有SourceCode
  171. gulp.task('backup-source', function() {
  172. return gulp.src('src/**/*').pipe(gulp_copy('./tmp_source'));
  173. });
  174.  
  175. // SASS編譯
  176. gulp.task('compile-sass', function() {
  177. gulp
  178. .src('src/**/*.scss')
  179. .pipe(gulp_sass().on('error', gulp_sass.logError)) // this will prevent our future watch-task from crashing on sass-errors
  180. .pipe(
  181. gulp.dest(function(file) {
  182. return file.base; // because of Angular 2's encapsulation, it's natural to save the css where the scss-file was
  183. })
  184. );
  185. });
  186.  
  187. // 壓縮CSS
  188. gulp.task('clean-css', function() {
  189. return gulp
  190. .src('src/**/*.css')
  191. .pipe(gulp_cleanCSS({ compatibility: 'ie8' }))
  192. .pipe(
  193. gulp.dest(function(file) {
  194. return file.base; // because of Angular 2's encapsulation, it's natural to save the css where the scss-file was
  195. })
  196. );
  197. });
  198.  
  199. gulp.task(
  200. 'export',
  201. ['export-package-json', 'export-grobal-css', 'restore', 'export-package'],
  202. function(done) {
  203. done();
  204. }
  205. );
  206.  
  207. // 恢復Source code
  208. gulp.task('restore', function() {
  209. return gulp.src('tmp_source/**/*').pipe(gulp_copy('./', { prefix: 1 }));
  210. });
  211.  
  212. // 複製頂層package.json與讀我、授權條款至輸出
  213. gulp.task('export-package-json', function() {
  214. return gulp
  215. .src(['package.json', '{README,readme}?(.md)', '{LICENSE|license}?(.md)'])
  216. .pipe(gulp_copy('./dist/'));
  217. });
  218.  
  219. // 複製全域CSS
  220. gulp.task('export-grobal-css', function() {
  221. console.log(
  222. angularConfig.apps[0].styles.map(x => angularConfig.apps[0].root + '/' + x)
  223. );
  224. return gulp
  225. .src(
  226. angularConfig.apps[0].styles.map(
  227. x => angularConfig.apps[0].root + '/' + x
  228. )
  229. )
  230. .pipe(gulp_copy('./dist/', { prefix: 999 }));
  231. });
  232.  
  233. // 匯出package
  234. gulp.task('export-package', function() {
  235. var copyFrom = './tmp_dist/' + modulePath;
  236. var level = copyFrom
  237. .replace(/\.\//g, '')
  238. .replace(/\/\//g, '')
  239. .split('/').length;
  240.  
  241. return gulp
  242. .src('./tmp_dist/' + modulePath + '/**/*')
  243. .pipe(gulp_copy('./dist/', { prefix: level }));
  244. });
  245.  
  246. ```
  247.  
  248. 4.在package.json中加入script以及main屬性,如要發行則必須要刪除`"private": true,`
  249. ```json
  250. "main": "index.js",
  251. "scripts": {
  252. "ngBuild": "gulp build"
  253. },
  254. "private": true //<--刪除這行
  255. ```
  256.  
  257. 5.修改**tsconfig.json**,以便輸出定義檔
  258. ```json
  259. "compilerOptions": {
  260. "declaration": true
  261. }
  262. ```
  263.  
  264. 6.將Angular組件引入src目錄後如要進行編譯請執行
  265. ```powershell
  266. npm run ngBuild
  267. ```
  268.  
  269. 7.如若要發行套件則輸入以下指令
  270. ```powershell
  271. npm publish dist
  272. ```
Add Comment
Please, Sign In to add comment