Angular 5 - 如何生成定义文件

时间:2017-11-15 16:37:00

标签: angular angular5 npm-link

我一直尝试了几种方法,但我无法理解如何为我的项目生成定义文件。我有两个angular-cli生成的应用程序A和B,我希望A使用B作为包(使用npm链接)。据我所知,我需要在项目B中创建一个index.ts文件,其中包含我要导出的所有模块并运行' ng build'命令。我已经看到只创建包但不创建定义文件,如何生成定义文件?这是正确的做法吗?

我尝试了其他一些选项,例如'汇总'和' ngmakelib'但是做这个简单的任务似乎很难。我们是否有一种简单的方法可以将Angular 5项目生成为库并从其他项目中使用这些库?

1 个答案:

答案 0 :(得分:1)

在较高的层次上,以下是创建可重用Angular模块所需的步骤(所有这些都是在没有webpack的情况下完成的):

  1. public_api.ts文件夹中创建src文件。这应该包含您导出的所有符号,以便您图书馆的用户可以执行以下操作:import { symbol } from 'your-library'

  2. src文件夹复制到build/dist文件夹,确保内嵌模板。我为此使用了gulpgulp-inline-ng2-template

  3. <强> gulpfile.js

        const gulp = require('gulp');
        const replace = require('gulp-replace');
        const inlineNg2Template = require('gulp-inline-ng2-template');
        const del = require('del');
    
        gulp.task('clean', function () {
            return del([
               "dist/**"
            ], { force: true });
        });
    
    
        gulp.task('copy-public-api', ['clean'], function () {
            return gulp.src([
                '../src/public_api.ts'
            ])
            .pipe(replace('./app', './src'))
            .pipe(gulp.dest('dist'))
    
        });
        gulp.task('copy-src', ['copy-public-api'], function () {
            return gulp.src([
               '../src/app/**/*.ts',
               '!../src/app/**/*.spec.ts'
            ])
            .pipe(inlineNg2Template({ base: '../src', useRelativePaths: true }))
            .pipe(gulp.dest('dist/src'))
        });
    

    <强> public_api.ts

        export * from './app/app.module';
        // ... other exports ...
    
    1. ngc创建tsconfig文件。您将使用ngc生成必要的元数据文件。以下是我使用的设置。该文件放置在&#34; build&#34;文件夹(注意typeRootspaths的相对路径。)
    2. <强>建立/ tsconfig.json

          {
              "compilerOptions": {
                  "baseUrl": ".",
                  "rootDir": ".",
                  "outDir": "",
                  "paths": {
                      "*": [
                          "../node_modules/*"
                      ]
                  },             
                  "declaration": true,
                  "stripInternal": true,
                  "noImplicitAny": true,
                  "strictNullChecks": true,
                  "noFallthroughCasesInSwitch": true,
                  "moduleResolution": "node",
                  "module": "es2015",
                  "target": "es5",
                  "lib": [
                      "es2015",
                      "dom"
                  ],
                  "skipLibCheck": true,
                  "typeRoots": [     
                      "../node_modules/@types/"  
                  ], 
                  "experimentalDecorators": true,
                  "emitDecoratorMetadata": true,
                  "sourceMap": true,
                  "inlineSources": true
              },
              "files": [
                  "dist/public_api.ts"
              ],
              "angularCompilerOptions": {
                  "annotateForClosureCompiler": true,
                  "strictMetadataEmit": false,
                  "skipTemplateCodegen": true,
                  "flatModuleOutFile": "index.js",
                  "flatModuleId": "ng-module-template"
              }    
      
          }
      

      angularCompilerOptions确保创建一个元数据文件(index.js)。

      1. 使用ngc从build文件夹编译模块。请务必安装@angular/compiler@angular/compiler-cli

        ../node_modules/.bin/ngc -p tsconfig.json
        
      2. 仅部署所需的文件。我从build\dist部署到dist

        gulp.task('build', [], function (done) {
            gulp.src([
                'dist/index.js',
                'dist/public_api.js',
                'dist/index.metadata.json',
                'dist/**/*.d.ts',
                '!../src/app/**/*.spec.ts'
            ], { base: 'dist' })
                .pipe(gulp.dest('../dist'))
                .on('end', function () {
                    del('dist/**', { force: true }).then(function () {
                        done();
                    });
                });
        });
        
      3. 确保修改package.json以指向index.js:

        {
          "name": "ng-module-template",
          "version": "1.0.0",
          "description": "",
          "main": "dist/index.js",
          "typings": "dist/index.d.ts",
        }
        
      4. 可选:创建捆绑包

        这是一个gulp构建目标,用于使用汇总和树木来编译和创建包:

        gulp.task('compile', ['copy-src'], function (done) {
            gulp.src('tsconfig.json')
                .pipe(shell(['"../node_modules/.bin/ngc" -p <%= file.path %>']))
                .on('end', function () {
                    del('node_modules/**', { force: true }).then(function () {
                        done();
                    });
                });
        });
        
        gulp.task('bundle', ['compile'], function (done) {
            var external = [
                '@angular/core',
                '@angular/common',
                '@angular/compiler',
                '@angular/core',
                '@angular/http',
                '@angular/platform-browser',
                '@angular/platform-browser-dynamic',
                '@angular/router',
                '@angular/router-deprecated'
            ];
        
            var globals = {
                '@angular/core': 'vendor._angular_core',
                '@angular/http': 'vendor._angular_http',
                '@angular/platform-browser': 'vendor._angular_platformBrowser',
                '@angular/platform-browser-dynamic': 'vendor._angular_platformBrowserDynamic',
                '@angular/router-deprecated': 'vendor._angular_routerDeprecated'
            };
        
            rollup.rollup({
                input: 'dist/index.js',
                onwarn: function (warning) {
                    if (warning.message.indexOf("treating it as an external dependency") > -1)
                        return;
        
        
                    console.warn(warning.message);
                }
        
            }).then(function (bundle) {
                var umd = bundle.write({
                    file: `dist/bundles/${pkg.name}.umd.js`,
                    format: 'umd',
                    exports: 'named',
                    name: pkg.name,
                    sourcemap: true,
                    external: external,
                    globals: globals
                });
                var cjs = bundle.write({
                    file: `dist/bundles/${pkg.name}.cjs.js`,
                    format: 'cjs',
                    exports: 'named',
                    name: pkg.name,
                    sourcemap: true,
                    external: external,
                    globals: globals
                });
                var amd = bundle.write({
                    file: `dist/bundles/${pkg.name}.amd.js`,
                    format: 'amd',
                    exports: 'named',
                    name: pkg.name,
                    sourcemap: true,
                    external: external,
                    globals: globals
                });
        
                var es = bundle.write({
                    file: `dist/index.es5.js`,
                    format: 'es',
                    exports: 'named',
                    name: pkg.name,
                    sourcemap: true,
                    external: external,
                    globals: globals
        
                });
        
                return Promise.all([umd, cjs, amd, es]).then(function () {
                    done();
                });
        
            });
        });
        

        源代码演示

        先决条件

          

        Angular5 +
          Git(如果要发布到本地文件夹,则在本地安装)

        https://github.com/angular-patterns/ng-module-template

        构建目标

        npm run dev

        开发

        npm run build

        用于生产应用程序构建(输出到dist文件夹)

        npm run build-module

        对于模块构建(输出到dist文件夹)

        npm run publish

        使用git发布到c:\packages。或者,运行npm publish以发布到npm

        npm run name-module - - (module-name)

        用于命名模块。这会修改源。

        从c:\ packages

        安装
        npm install c:\packages\<module-name>