码迷,mamicode.com
首页 > 其他好文 > 详细

[Angular] Angular Elements Intro

时间:2018-07-31 11:16:46      阅读:173      评论:0      收藏:0      [点我收藏+]

标签:cat   put   info   ons   ati   imp   dex   pre   amp   

Make sure install the latest Angular v6 with Angular CLI. Checkout ght Github for the code.

 

1. Create a new application:

ng new elementApp

 

2. Install @angular/elements package:

npm i @angular/elements --save
npm i @webcomponents/custom-elements --save

 

3. Import polyfills in polyfills.ts:

/***************************************************************************************************
 * APPLICATION IMPORTS
 */

import ‘@webcomponents/custom-elements/src/native-shim‘;
import ‘@webcomponents/custom-elements/custom-elements.min‘;

 

4. Generate a component:

ng g c user-poll

 

5. Conver the element to angular elements:

import { BrowserModule } from ‘@angular/platform-browser‘;
import { NgModule, Injector } from ‘@angular/core‘;
import { createCustomElement } from ‘@angular/elements‘;
import { AppComponent } from ‘./app.component‘;
import { UserPollComponent } from ‘./user-poll/user-poll.component‘;

@NgModule({
  declarations: [ UserPollComponent],
  entryComponents: [UserPollComponent],
  imports: [BrowserModule]
})
export class AppModule {
  constructor(private injector: Injector) {}

  ngDoBootstrap() {
    const el = createCustomElement(UserPollComponent, { injector: this.injector });
    customElements.define(‘user-poll‘, el);
   }
}

 

6. Build process:

Install:

npm install fs-extra concat --save-dev
//elementApp/build-script.js

const fs = require(‘fs-extra‘);
const concat = require(‘concat‘);

(async function build() {

    const files =[
      ‘./dist/elementApp/polyfills.js‘,
      ‘./dist/elementApp/runtime.js‘,
      ‘./dist/elementApp/styles.css‘,
      ‘./dist/elementApp/main.js‘
    ]

    await fs.ensureDir(‘elements‘)

    await concat(files, ‘elements/user-poll.js‘)
    console.info(‘Elements created successfully!‘)

})()
//package.json

"build:elements": "ng build --prod --output-hashing none && node build-script.js"

Run:

npm run build:element

技术分享图片

After concat all the files, we got:

技术分享图片

 

 Then we can use it in a test index.html:

<user-poll></user-poll>
<script src="elements/user-poll.js"></script>

技术分享图片

 


 

 

Step 6. Now there is a new library can help to simplfy the process. checkout ngx-build-plus 

 

[Angular] Angular Elements Intro

标签:cat   put   info   ons   ati   imp   dex   pre   amp   

原文地址:https://www.cnblogs.com/Answer1215/p/8992242.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!