问题描述:

I have two separate Angular 2 apps which both are using exact same component. This has resulted in code duplication which I don't like. Is there a was to host the common component somewhere and remotely load them in these consumer apps? The same idea as CDN hosted files.

网友答案:

You could publish your components on npm. This will not load them remotely, but you can AOT compile them in your app and still have pretty good results in terms of size and speed.

You could also put them in a lazy-loaded module, this way the components would be loaded at a later time.

To publish a component to npm you need to do the following:

  1. Create your components
  2. At the root, create an index.ts with the following export

export * from './src/mycomponent.component';

  1. Install Typescript to compile the .ts to .js

npm install --save-dev typescript

  1. In package.json create a prepublish script under scripts to compile your component before publishing

    "scripts": {
      "prepublish": "tsc"
    }
    
  2. Create a tsconfig.json

    {
        "compilerOptions": {
            "noImplicitAny": true,
            "module": "commonjs",
            "target": "ES5",
            "emitDecoratorMetadata": true,
            "experimentalDecorators": true,
            "sourceMap": true,
            "declaration": true
        },
        "files": [
            "mycomponent.component.ts"
        ],
        "exclude": [
            "node_modules"
        ]
    }
    
  3. Add typings information to package.json

    "typings": "./mycomponent.component.d.ts",
    
  4. Publish on npm with

    npm publish
    

This will run the Typescript compiler, before publishing the files to npm.

PS: You might also want to add the following lines to a .npmignore file, so only the typings get published, but not the source.

# Ignored files
*.ts
!*.d.ts
相关阅读:
Top