<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Kevin Boosten on Medium]]></title>
        <description><![CDATA[Stories by Kevin Boosten on Medium]]></description>
        <link>https://medium.com/@kevinboosten?source=rss-6a24c92e65b0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*h3BpUbiKv2X8M6JTa58hWQ.jpeg</url>
            <title>Stories by Kevin Boosten on Medium</title>
            <link>https://medium.com/@kevinboosten?source=rss-6a24c92e65b0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 20:38:26 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kevinboosten/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How I use an OpenAPI spec in my Angular projects]]></title>
            <link>https://kevinboosten.medium.com/how-i-use-an-openapi-spec-in-my-angular-projects-90be4b327bcc?source=rss-6a24c92e65b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/90be4b327bcc</guid>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[openapi-specification]]></category>
            <category><![CDATA[swagger]]></category>
            <category><![CDATA[open-api]]></category>
            <category><![CDATA[developer-experience]]></category>
            <dc:creator><![CDATA[Kevin Boosten]]></dc:creator>
            <pubDate>Thu, 11 Feb 2021 00:00:00 GMT</pubDate>
            <atom:updated>2021-05-20T07:33:26.692Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*jx9mBPZJDmUjV3uo.png" /></figure><p>If you are working on a project that has an OpenAPI spec, then you can generate your Angular Code and even generate a simulator for development and test purposes. This reduces time and complexity of integrating with an OpenAPI gateway tremendously. Let me show you how I use OpenAPI to boost up my productivity!</p><p>Here is a brief introduction if you’re not familiar with <a href="https://swagger.io/specification/">OpenAPI</a> in general:</p><blockquote>The OpenAPI Specification (OAS) defines a standard, language-agnostic interface to RESTful APIs which allows both humans and computers to discover and understand the capabilities of the service without access to source code, documentation, or through network traffic inspection. When properly defined, a consumer can understand and interact with the remote service with a minimal amount of implementation logic.</blockquote><p>Or maybe you know <a href="https://swagger.io/">Swagger</a>, so what’s the difference? Check it out here: <a href="https://swagger.io/blog/api-strategy/difference-between-swagger-and-openapi/">Differences between Swagger and OpenAPI</a>.</p><h3>OpenAPI Generator</h3><p>So your backend colleague gave you the endpoint of their api so you can start integrating your web application with some real data. So what will be your next step? You’re quite a Typescript enthousiast and want to make sure that your web application has some type safety, so you start typing out some TS interfaces that we can use. Okay, check ✅. Next step? Maybe add some abstraction and reusability to your stack? So you create an Angular Service that uses the <a href="https://angular.io/api/common/http/HttpClient">HttpClient</a> and so wraps the actual endpoint. Sounds good and eventually this will be a good approach. But it feels a bit repetitive to do this for every project again. Besides that, I think you can spend your time better on building actual features for your application, right?</p><p>So what if we could automate these steps to save some precious time 🧐? In a few steps we can generate Angular specific code based on our OpenAPI spec. Let’s get started 👨‍💻!</p><h4>Create Angular app</h4><p>First install the Angular CLI if you don’t have this installed already:</p><pre>npm install -g @angular/cli</pre><p>Start with a new angular app and choose the default options:</p><pre>ng new angular-openapi-demo<br>cd angular-openapi-demo</pre><p>Start the application to verify everything went well:</p><pre>ng serve</pre><h4>Create an OpenAPI yaml file</h4><p>A well defined api comes with some documentation. An api built with OpenAPI comes with a yaml, or JSON, spec that describes the actual api. We can build this spec by creating a yaml file in our application. As I said before, you probably will receive this spec from your backend developer. But we will be creating our own for this tutorial. In order to have a real working api, we will use the well known <a href="https://jsonplaceholder.typicode.com/">JSON Placeholder</a> public test api.</p><p>Add a file openapi.yaml to the root of your application and add the following content:</p><blockquote><em>You can also download the file from the </em><a href="https://github.com/Boosten/angular-openapi-demo/blob/master/openapi.yaml"><em>demo repo</em></a></blockquote><pre>openapi: 3.0.0<br>info:<br>  title: JSON Placeholder OpenAPI<br>  description: Example spec of the well known JSON Placeholder website<br>  version: 0.1.9<br>servers:<br>  - url: https://jsonplaceholder.typicode.com<br>paths:<br>  /posts:<br>    get:<br>      tags: [&#39;posts&#39;]<br>      summary: Returns a list of Posts.<br>      description: Optional extended description in CommonMark or HTML.<br>      operationId: GetPosts<br>      responses:<br>        &#39;200&#39;:<br>          description: A JSON array of Posts<br>          content:<br>            application/json:<br>              schema:<br>                type: array<br>                items:<br>                  $ref: &#39;#/components/schemas/Post&#39;<br>components:<br>  schemas:<br>    Post:<br>      required:<br>        - id<br>        - userId<br>        - title<br>        - body<br>      type: object<br>      properties:<br>        id:<br>          type: number<br>          description: record id<br>          example: 1<br>        userId:<br>          type: string<br>          description: unique user identifier<br>          example: 2<br>        title:<br>          type: string<br>          description: title of this Post<br>          example: sunt aut facere repellat provident occaecati excepturi optio reprehenderit<br>        body:<br>          type: string<br>          description: description of this post<br>          example: quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto</pre><p>I think that this kind of documenting is quite self explanatory, but let’s discuss a couple of things:</p><ul><li>Post: this is a way of defining a model. We can use this model by using the <a href="https://swagger.io/docs/specification/using-ref/">$ref</a> keyword.</li><li>servers: here we define one or more base URLs for our spec.</li><li>example: give a hint about what value to expect. Later on I will explain you why this is handy when creating a simulator.</li></ul><blockquote><em>Tip! Make working with OpenApi spec easier in VSCode by installing the </em><a href="https://marketplace.visualstudio.com/items?itemName=Arjun.swagger-viewer"><em>Swagger Viewer extension</em></a></blockquote><blockquote><em>Curious about what the OpenApi spec has to offer? Check out the </em><a href="https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.2.md"><em>OpenAPI Specification</em></a></blockquote><h4>Generate Angular Services</h4><p>We’re going to generate our Angular code with the CLI of <a href="https://github.com/OpenAPITools/openapi-generator-cli">openapi-generator</a>. We can install this via npm as devDependency:</p><pre>npm i @openapitools/openapi-generator-cli -D</pre><p>This packages has a lot of <a href="https://openapi-generator.tech/docs/generators">generators available</a>, we’re going to use the <a href="https://openapi-generator.tech/docs/generators/typescript-angular">typescript-angular</a> one.</p><p>Add a npm script to your package.json file for more convenient usage:</p><pre>{<br>  &quot;scripts&quot;: {<br>    // other scripts<br>    &quot;generate:api&quot;: &quot;openapi-generator-cli generate -i ./openapi.yaml -g typescript-angular -o src/app/core/api/v1&quot;<br>  }<br>}</pre><p>We use the default configuration over here. But you can customize this based on your needs.</p><p>One example could be the option removeOperationIdPrefix to prevent redundant method names. Take for example the following operationId in your spec:</p><pre>operationId: Posts_GetPosts</pre><p>The generator will use the operationId to determine the Angular Service name and the method name. If we use the default configuration, our class will look like this:</p><pre><em>// this looks redundant</em><br><strong>export</strong> <strong>class</strong> PostsService {<br>  <strong>public</strong> postsGetPosts() {}<br>}<br><br><em>// and when you invoke it, it is redundant and looks weird...</em><br><strong>const</strong> postsService <strong>=</strong> <strong>new</strong> PostsService();<br>postsService.postsGetPosts();</pre><p>Using the arguments -p=removeOperationIdPrefix=true will remove the Posts_ part of the operationId: Posts_GetPosts</p><pre><em>// this looks redundant</em><br><strong>export</strong> <strong>class</strong> PostsService {<br>  <strong>public</strong> getPosts() {}<br>}</pre><p>That already looks better to me! As I said, there are plenty of configuration options. And you probably will be using some of them from time to time depending on the spec you receive.</p><p>Next step is to actually generate our code with our custom npm script:</p><pre>npm run generate:api</pre><p>We now have the following directory structure because we told the generator to output (-o) to the src/app/core/api/v1 directory:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/878/0*S_lJapjs_i84cykt.png" /></figure><h4>Use generated NgModule and services</h4><p>The most important parts of the generated code are the following files:</p><ul><li>posts.services.ts: the actual Angular service.</li><li>post.ts: a TS interface that matches the Post model of our OpenAPI spec.</li><li>api.module.ts: a NgModule that can be imported to your AppModule.</li><li>README.md: <a href="https://github.com/Boosten/angular-openapi-demo/blob/master/src/app/core/api/v1/README.md">README</a> file with usage instructions.</li></ul><p>Add this ApiModule to your AppModule. This will use the &#39;default&#39; server endpoint that is available in your openapi.yaml. You can see that in the generated posts.service.ts:</p><pre>@Injectable({<br>  providedIn: &#39;root&#39;,<br>})<br><strong>export</strong> <strong>class</strong> PostsService {<br>  <strong>protected</strong> basePath <strong>=</strong> &#39;https://jsonplaceholder.typicode.com&#39;;<br>  <em>// ...</em><br>}</pre><pre><em>// without configuring providers</em><br><strong>import</strong> { ApiModule } <strong>from</strong> &#39;&#39;;<br><strong>import</strong> { HttpClientModule } <strong>from</strong> &#39;@angular/common/http&#39;;<br><br>@NgModule({<br>  imports: [<br>    ApiModule,<br>    <em>// make sure to import the HttpClientModule in the AppModule only,</em><br>    <em>// see https://github.com/angular/angular/issues/20575</em><br>    HttpClientModule,<br>  ],<br>  declarations: [AppComponent],<br>  providers: [],<br>  bootstrap: [AppComponent],<br>})<br><strong>export</strong> <strong>class</strong> AppModule {}</pre><p>If you want to override or provide a different endpoint, you can do this by passing in a factory function in the <a href="https://angular.io/guide/singleton-services#forRoot">forRoot</a> method of the ApiModule:</p><pre><strong>import</strong> { NgModule } <strong>from</strong> &#39;@angular/core&#39;;<br><strong>import</strong> { AppComponent } <strong>from</strong> &#39;./app.component&#39;;<br><strong>import</strong> {<br>  ApiModule,<br>  Configuration,<br>  ConfigurationParameters,<br>} <strong>from</strong> &#39;./core/api/v1&#39;;<br><br><strong>export</strong> <strong>function</strong> apiConfigFactory(): Configuration {<br>  <strong>const</strong> params: ConfigurationParameters <strong>=</strong> {<br>    basePath: &#39;https://staging.jsonplaceholder.typicode.com&#39;,<br>  };<br>  <strong>return</strong> <strong>new</strong> Configuration(params);<br>}<br><br>@NgModule({<br>  imports: [ApiModule.forRoot(apiConfigFactory)],<br>  declarations: [AppComponent],<br>  providers: [],<br>  bootstrap: [AppComponent],<br>})<br><strong>export</strong> <strong>class</strong> AppModule {}</pre><p>And we can go one step further by moving the basePath to the Angular environment files:</p><pre><em>// environment.ts</em><br><strong>export</strong> <strong>const</strong> environment <strong>=</strong> {<br>  production: <strong>false</strong>,<br>  basePath: &#39;https://jsonplaceholder.typicode.com&#39;,<br>};</pre><pre><em>// environment.prod.ts</em><br><strong>export</strong> <strong>const</strong> environment <strong>=</strong> {<br>  production: <strong>true</strong>,<br>  basePath: &#39;https://jsonplaceholder.typicode.com&#39;,<br>};</pre><p>So now we can import the environment.basePath variable to configure our ApiModule.</p><blockquote>There are even more variables in the Configuration object that can be set, see Configuration.ts on the demo repo.</blockquote><pre><strong>import</strong> { NgModule } <strong>from</strong> &#39;@angular/core&#39;;<br><strong>import</strong> { environment } <strong>from</strong> &#39;../environments/environment&#39;;<br><strong>import</strong> { AppComponent } <strong>from</strong> &#39;./app.component&#39;;<br><strong>import</strong> {<br>  ApiModule,<br>  Configuration,<br>  ConfigurationParameters,<br>} <strong>from</strong> &#39;./core/api/v1&#39;;<br><br><strong>export</strong> <strong>function</strong> apiConfigFactory(): Configuration {<br>  <strong>const</strong> params: ConfigurationParameters <strong>=</strong> {<br>    basePath: environment.basePath,<br>  };<br>  <strong>return</strong> <strong>new</strong> Configuration(params);<br>}<br><br>@NgModule({<br>  imports: [ApiModule.forRoot(apiConfigFactory)],<br>  declarations: [AppComponent],<br>  providers: [],<br>  bootstrap: [AppComponent],<br>})<br><strong>export</strong> <strong>class</strong> AppModule {}</pre><h4>Usage example</h4><p>We can now start using our generated services in our application! Change your app.component.ts to this:</p><pre><strong>import</strong> { Component } <strong>from</strong> &#39;@angular/core&#39;;<br><strong>import</strong> { PostsService } <strong>from</strong> &#39;./core/api/v1&#39;;<br><br>@Component({<br>  selector: &#39;app-root&#39;,<br>  templateUrl: &#39;./app.component.html&#39;,<br>  styleUrls: [&#39;./app.component.css&#39;],<br>})<br><strong>export</strong> <strong>class</strong> AppComponent {<br>  <em>// Create a `cold` observable - we will be subscribing to this observable in the template</em><br>  posts$ <strong>=</strong> <strong>this</strong>.postService.getPosts();<br><br>  <em>// Inject the generated Angular service as a dependency of this class</em><br>  <strong>constructor</strong>(<strong>private</strong> postService: PostsService) {}<br>}</pre><p>And in your app.component.html we can use the posts$ variable by subscribing to it with the <a href="https://angular.io/api/common/AsyncPipe">async</a> pipe:</p><pre>&lt;ul&gt;<br>  &lt;li *ngFor=&quot;let post of posts$ | async as list&quot;&gt;<br>    &lt;h2&gt; - &lt;/h2&gt;<br>    &lt;p&gt;&lt;/p&gt;<br>  &lt;/li&gt;<br>&lt;/ul&gt;</pre><p>Your browser should now show you a list of Posts from JsonPlaceholder:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/458/0*UDxaeDzZxIG4UKgt.png" /></figure><p>🎉 Done! That was all we needed to do to generate ourselves some Angular services and spare us some time.</p><h4>Next steps</h4><p>In this example I’m generating and putting my code in my project’s repository. That’s fine for most of my projects because we’re using monorepos and also using client specific api’s. Another approach could be to publish your generated code as a npm package that can be installed by others. These steps are also described by the OpenAPI generator itself in the <a href="https://github.com/Boosten/angular-openapi-demo/blob/master/src/app/core/api/v1/README.md">README</a>. So it depends on your needs which approach fits better.</p><h3>Simulator</h3><p>Now that we’ve generated our Angular services, let’s have a look at how we can utilize the OpenAPI spec even better in our front-end application stack! What we’re going to use for this is a great package called: <a href="https://github.com/anttiviljami/openapi-backend">OpenAPI Backend</a> from <a href="https://medium.com/u/b808483b9fff">Viljami Kuosmanen ⭐</a> (<a href="https://github.com/anttiviljami">GitHub</a>).</p><p>As Viljami describes it in one sentence:</p><blockquote>OpenAPI Backend is a Framework-agnostic middleware tool for building beautiful APIs with OpenAPI Specification.</blockquote><p>OpenAPI Backend has a couple of useful features, but the feature that we’re going to use is the <a href="https://github.com/anttiviljami/openapi-backend#mocking-api-responses">auto-mocking responses</a> behavior.</p><h4>Setting up simulator project</h4><p>The simulator project will be an independent project but within your current directory structure and so it will also be part of your git repo. So actually we’re going to create a monorepo: a single repository that contains all our code. I’m an advocate when it comes down to monorepos. If you want to learn more about useful tooling around monorepos, then you certainly should check out the following tools:</p><ul><li><a href="https://lerna.js.org/">Lerna</a> — easy to use, quick to set up.</li><li><a href="https://nx.dev/">NX.dev</a> — managing monorepos like a pro 😉.</li></ul><p>I’m not going to use any of these tools for the sake of this tutorial.</p><p>Let’s get started by creating a directory where our simulator will live and go to the directory:</p><pre>mkdir simulator<br>cd simulator</pre><p>Initialize a new npm project to generate a package.json file:</p><pre>npm init -y <em># -y will answer the questions with yes</em></pre><p>Install the required dependencies:</p><pre>npm i openapi-backend <em># the actual dependency we need :-)</em><br>npm i --save-dev typescript <em># we will be using Typescript, so transpilation needs to be done</em><br>npm i express <em># To serve our simulated endpoints</em><br>npm i --save-dev @types/express <em># typescript types for express</em><br>npm i cors<br>npm i --save-dev @types/cors</pre><p>As you can see we’re using Typescript. We need a tsconfig.json file, which you can initialize with the following command:</p><pre>npx tsc --init</pre><blockquote>We used the locally installed typescript compiler by running it via <a href="https://docs.npmjs.com/cli/v7/commands/npx">npx</a>. It will run the tsc bin from your local node_modules because we installed it as our devDependency<em>.</em></blockquote><p>Open the generated tsconfig.json file and configure the output directory. Your file should look like this:</p><pre>{<br>  &quot;compilerOptions&quot;: {<br>    &quot;target&quot;: &quot;es5&quot;,<br>    &quot;module&quot;: &quot;commonjs&quot;,<br>    &quot;outDir&quot;: &quot;./dist&quot;, /* Redirect output structure to the directory. */<br>    &quot;strict&quot;: <strong>true</strong>, /* Enable all strict type-checking options. */<br>    &quot;esModuleInterop&quot;: <strong>true</strong>, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies &#39;allowSyntheticDefaultImports&#39;. */<br>    &quot;skipLibCheck&quot;: <strong>true</strong>, /* Skip type checking of declaration files. */<br>    &quot;forceConsistentCasingInFileNames&quot;: <strong>true</strong> /* Disallow inconsistently-cased references to the same file. */<br>   }<br>}</pre><p>We’re almost there. Update the npm scripts in your package.json so we can build and run our simulator. Your package.json should now look like this:</p><pre>{<br>  &quot;name&quot;: &quot;simulator&quot;,<br>  &quot;version&quot;: &quot;1.0.0&quot;,<br>  &quot;description&quot;: &quot;&quot;,<br>  &quot;main&quot;: &quot;index.js&quot;,<br>  &quot;scripts&quot;: {<br>    &quot;start&quot;: &quot;tsc &amp;&amp; node dist/index.js&quot;<br>  },<br>  &quot;keywords&quot;: [],<br>  &quot;author&quot;: &quot;&quot;,<br>  &quot;license&quot;: &quot;ISC&quot;,<br>  &quot;dependencies&quot;: {<br>    &quot;cors&quot;: &quot;^2.8.5&quot;,<br>    &quot;express&quot;: &quot;^4.17.1&quot;,<br>    &quot;openapi-backend&quot;: &quot;^3.9.1&quot;<br>  },<br>  &quot;devDependencies&quot;: {<br>    &quot;@types/cors&quot;: &quot;^2.8.10&quot;,<br>    &quot;@types/express&quot;: &quot;^4.17.11&quot;,<br>    &quot;typescript&quot;: &quot;^4.2.3&quot;<br>  }<br>}</pre><p>And the last thing we need to do is to actually create a simulator instance with the openapi-backend package. Do this by adding a file called index.ts to your simulator directory and add this content to it:</p><pre><strong>import</strong> cors <strong>from</strong> &#39;cors&#39;;<br><strong>import</strong> express <strong>from</strong> &#39;express&#39;;<br><strong>import</strong> OpenAPIBackend, { Request } <strong>from</strong> &#39;openapi-backend&#39;;<br><br><em>// Create api with your definition file or object. This points to the openapi yaml spec</em><br><strong>const</strong> api <strong>=</strong> <strong>new</strong> OpenAPIBackend({ definition: &#39;../openapi.yaml&#39; });<br><br><em>// Register your framework specific request handlers here</em><br>api.register({<br>  notFound: (c, req, res) <strong>=&gt;</strong> res.status(404).json({ err: &#39;not found&#39; }),<br>  notImplemented: (c, req, res) <strong>=&gt;</strong> {<br>    <strong>const</strong> { status, mock } <strong>=</strong> c.api.mockResponseForOperation(<br>      c.operation.operationId <strong>??</strong> &#39;&#39;<br>    );<br>    <strong>return</strong> res.status(status).json(mock);<br>  },<br>});<br><br><em>// Initialize the backend</em><br>api.init();<br><br><em>// Initialize the express server that will serve the api backend</em><br><strong>const</strong> port <strong>=</strong> 9000;<br><strong>const</strong> app <strong>=</strong> express();<br>app.use(express.json());<br><em>// Allow cors on all origins - its okay to do this for our simulator</em><br>app.use(cors());<br>app.use((req, res) <strong>=&gt;</strong> api.handleRequest(req <strong>as</strong> Request, req, res));<br>app.listen(port, () <strong>=&gt;</strong><br>  console.info(`api listening at http://localhost:${port}`)<br>);</pre><p>Registering the <a href="https://github.com/anttiviljami/openapi-backend/blob/master/DOCS.md#notimplemented-handler">notImplemented</a> handler that we will be using to mock the response is the most important part of this configuration. As the documentation states: The notImplemented handler gets called by .handleRequest() if no other Operation Handler has been registered for the matched operation. The <a href="https://github.com/anttiviljami/openapi-backend/blob/master/DOCS.md#mockresponseforoperationoperationid-opts">mockResponseForOperation</a> method will then mock a response based on the available example data.</p><h4>Running the simulator</h4><p>Now run npm start in your simulator directory and open your browser on <a href="http://localhost:9000/posts">http://localhost:9000/posts</a> to see some Posts 🚀! The response should look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CnyhW-Kbs_pXuQDM.png" /></figure><p>So where is this data actually coming from? Do you remember the example keyword that I mentioned earlier? That&#39;s how we can return some useful response data to our requests. Here you can check out the official documentation about this <a href="https://swagger.io/docs/specification/adding-examples/">example keyword</a>.</p><h4>Using the simulator in our Angular app</h4><p>Now that we’ve our simulator project configured and running, we can use it in our Angular app. Open the environment.ts file located at: src/environments/environment.ts and change the basePath property to our local running simulator. You file should look like this:</p><pre><strong>export</strong> <strong>const</strong> environment <strong>=</strong> {<br>  production: <strong>false</strong>,<br>  basePath: &#39;http://localhost:9000&#39;,<br>};</pre><blockquote>This is the default environment file that Angular will use when you run the project with npm start or ng serve without any configuration parameters. You could add a specific environment configuration. Check out the official docs to learn more: <a href="https://angular.io/guide/build#configure-environment-specific-defaults">https://angular.io/guide/build#configure-environment-specific-defaults</a></blockquote><p>If you still have your Angular app running, then you should now see a single Post record being displayed in your browser. Otherwise restart your Angular app by running npm start in the root of your application. Our Angular application is now running against a local simulator!</p><h4>Enhancing DX (Developer Experience)</h4><p>Angular applications already uses the npm start command to eventually run ng serve. We need to make some adjustmenst in order to start our Angular application and simultanously start our simulator. I really appreciate it, and actually expect it, when I only have to run two commands to start the project: npm i &amp;&amp; npm start. Why? Nobody wants to have some superfluous starter doc that you need to read, handle mentally and do all kinds of set up tasks. To give your project a first good impression it should be ready to use within seconds! I&#39;m not saying you should not have a README.md file, the opposite! The README file could describe other helpful information that your reader should know (e.g. different configurations).</p><p>So what’s the problem with the repo that we created along this tutorial? As a developer you now need to:</p><ol><li>Run the Angular app via npm start in the root of your application</li><li>And start the simulator via npm start in the subdirectory simulator.</li></ol><p>In practice this requires the developer to open two terminal windows/tabs and run the commands. Not a great Developer Experience if you ask me. We can do better!</p><p>So let’s assume that we always want to run against the simulator in the default configuration, so when running the npm start command. We need to be able to start two tasks in parallel. And maybe you&#39;re already quite familiar with npm, but there&#39;s a package for that called: <a href="https://www.npmjs.com/package/npm-run-all">npm-run-all</a>.</p><p>Install it as a devDependency in the root of our project:</p><pre>npm install npm-run-all --save-dev</pre><p>Now open the package.json of our root project and alter the scripts section and make it like this by adding two scripts and changing the start script:</p><pre>&quot;start&quot;: &quot;npm-run-all --parallel start:app start:simulator&quot;,<br>&quot;start:app&quot;: &quot;ng serve&quot;,<br>&quot;start:simulator&quot;: &quot;npm --prefix simulator start&quot;,</pre><p>I guess the scripts do explain themselves, but here’s a brief description:</p><ul><li>start will now use the npm-run-all package to run two other npm scripts. The --parallel flag will run them in parallel.</li><li>start:app will start the Angular application.</li><li>start:simulator will start the simulator. Because its located in a subdirectory, we need to pass the --prefix argument to npm to point it to the simulator directory.</li></ul><p>Running the npm start command from the root should now start our Angular app + start the local simulator! Do not forget to update your README.md file with a sidenote about this behavior.</p><h4>Custom handlers</h4><p>You might have noticed that our simulator only returns a single record on an endpoint that could return multiple records. This is fine for some situations, but sometimes you’re developing a new feature that incorporates a list of items, or Posts in our context. Returning a single Post will not help you very much if you want to see how your list is working when multiple items are in it. Think about applying staggered animations on lists, filling the available space etc. In this situation the example data is not sufficient for our use case. What we can do is providing specific handlers for our OpenApi operations. A simple example for our Posts api is this:</p><pre>api.register(&#39;GetPosts&#39;, <strong>function</strong> (c, req, res) {<br>  <strong>return</strong> res.status(200).json([<br>    {<br>      id: 1,<br>      userId: 1,<br>      title: &#39;a&#39;,<br>      body: &#39;a&#39;,<br>    },<br>    {<br>      id: 2,<br>      userId: 2,<br>      title: &#39;b&#39;,<br>      body: &#39;b&#39;,<br>    },<br>  ]);<br>});</pre><p>You should add this to your simulator/index.ts file before app.init().</p><p>This way we created our very own response for the endpoint that is described in our api spec file. Great for developing and testing purposes if you ask me!</p><p>Check the docs for more info: <a href="https://github.com/anttiviljami/openapi-backend/blob/master/DOCS.md#registeroperationid-handler">https://github.com/anttiviljami/openapi-backend/blob/master/DOCS.md#registeroperationid-handler</a></p><blockquote>When you are going to provide or ‘override’ multiple endpoints, make sure that you keep your simulator code maintainable: so splitting up custom handlers in separate files and keeping your index.ts file clean.</blockquote><h3>Conclusion</h3><p>The OpenAPI spec is already very helpful to describe your api’s. I showed you how I utilize this spec to generate code in our Angular application and generate a simulator that we can use for development purposes. What I did not describe is how I use this same simulator to act as an api for my integration tests that I run with <a href="https://www.cypress.io/">Cypress</a>. Another great use case for your OpenAPI spec!</p><p>So, what else could you do with it? Let me know!</p><p><em>Originally published at </em><a href="https://www.kevinboosten.dev/how-i-use-an-openapi-spec-in-my-angular-projects"><em>https://www.kevinboosten.dev</em></a><em> on February 11, 2021.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=90be4b327bcc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to use Angular environment files in your Azure DevOps multi-stage yml release pipeline]]></title>
            <link>https://kevinboosten.medium.com/how-to-use-angular-environment-files-in-your-azure-devops-multi-stage-yml-release-pipeline-f78d2af2b2e9?source=rss-6a24c92e65b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/f78d2af2b2e9</guid>
            <category><![CDATA[pipeline]]></category>
            <category><![CDATA[microsoft]]></category>
            <category><![CDATA[ci-cd-pipeline]]></category>
            <category><![CDATA[azure-devops]]></category>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[Kevin Boosten]]></dc:creator>
            <pubDate>Sat, 16 May 2020 00:00:00 GMT</pubDate>
            <atom:updated>2021-05-18T20:03:20.477Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*6SYiaIa1V9Zn6rh6.png" /></figure><p>Angular has the concept of environment files that can be used to configure environment specific values. There are multiple ways to handle environments in your Angular web application.</p><ol><li>Create an environment specific .ts file and rebuild the complete application per environment. (e.g. environment.ts, environment.tst.ts, environment.stg.ts, environment.prd.ts). This works, but has the drawback that we need to rebuild the complete application when we go from staging to production. I don&#39;t think we want that.</li><li>Put your environment settings in a config.json file in your assets directory and request this file at runtime via the HttpClient during the start up. You could use the APP_INITIALIZER to make sure the environment settings are available before your application code is executed.<br>There are already enough articles about this approach. But it introduces extra code and start up dependencies because we’ve to wait for the config.json file to load over http. Of course this is negligible if we compare it to all the other files, but still it’s another request the browser has to make.</li><li>Or….just use the default environment files and make use of replacement tokens!</li></ol><p>I’ll show you how to do this in a Azure DevOps multi-stage yml pipeline. So besides a way to handle environments in your Angular app, you’ll also learn something about Azure DevOps multi-stage yml release pipelines!</p><h3>Start with an Angular app</h3><p>The first thing we need is a minimal Angular app. So let’s start with that:</p><pre>ng new azure-angular-release-demo --minimal --routing<strong>=</strong>false</pre><p>In your project you will find the default generated environment.ts and environment.prod.ts files. Don&#39;t loose them, we&#39;ll need them shortly 😉</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ELKN6eHrPj80-7gt.png" /></figure><p>Push this repo to your Github or Azure DevOps account so you can use it in Azure DevOps.</p><h3>Create Azure DevOps project</h3><p>I assume that you’re already in the ecosystem of Microsoft and you’ve got a Organization where you can create a new project. Otherwise consult the <a href="https://docs.microsoft.com/en-us/azure/devops/organizations/projects/create-project?view=azure-devops&amp;tabs=preview-page">docs</a>.</p><h4>Create initial pipeline</h4><p>Now that we have an Angular app and our project set up, we can configure our pipeline. You can do this via the portal or simply create a file azure-pipelines.yml in the root of your repository and add the following content to it:</p><pre>trigger:<br>  - master<br><br>pool:<br>  vmImage: &#39;ubuntu-latest&#39;<br><br>steps:<br>  - script: echo Hello, world!<br>    displayName: &#39;Run a one-line script&#39;</pre><p>For this demo I’m starting from the portal:</p><ul><li>In your DevOps project navigate to Pipelines and select Create Pipeline</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*K_rNW2ZyomaLLxy2.png" /></figure><ul><li>Choose the location where you code is. In this demo I used GitHub.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*nk3pdTD-x2ve3L-L.png" /></figure><ul><li>Select your repository</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tLZl4jP7q5yDGzDn.png" /></figure><ul><li>Choose the Starter pipeline</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*37Up9cYQu0gM9YCn.png" /></figure><ul><li>Eventually we want this in our pipeline to start with</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ddXDtq_iCl4pfshd.png" /></figure><ul><li>Save and run your pipeline to see if it works</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3DNn0sE9cFx--Kxu.png" /></figure><h4>Change to multi-stage pipeline</h4><p>Multi-stage pipelines are the new way to configure your release via code. We were already using the azure-pipeline.yml file to define our build steps, but now we can also use it to deploy our application to several environments. The &#39;classic&#39; way to do this in Azure DevOps is by configuring a release via the portal. This configuration will not be saved to your repository.</p><p>Multi-stage pipelines are still in preview, so it’s possible that you have to toggle the preview feature. But at the time of writing I do not see the feature toggle anymore, so maybe it’s not in preview anymore 🎉.</p><p>Check their website for more information about <a href="https://docs.microsoft.com/en-us/azure/devops/pipelines/process/stages?view=azure-devops&amp;tabs=yaml">multi-stage pipelines</a>.</p><p>We are now going to change our starter pipeline to a multi-stage pipeline with three stages. Copy this code to your azure-pipelines.yml file:</p><pre>trigger:<br>  - master<br><br>pool:<br>  vmImage: &#39;ubuntu-latest&#39;<br><br>stages:<br>  - stage: build<br>    jobs:<br>      - job:<br>        steps:<br>          - script: echo Hello, world!<br><br>  - stage: deploy_dev<br>    displayName: Deploy to development<br>    jobs:<br>      - job:<br>        steps:<br>          - script: echo Hello, world!<br><br>  - stage: deploy_prod<br>    displayName: Deploy to production<br>    jobs:<br>      - job:<br>        steps:<br>          - script: echo Hello, world!</pre><p>After committing your changes a new build will start, first thing you will notice are the extra green circles. These are our <em>stages</em>. We now own three stages, all managed by our yml file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*s0ldj2Jn088PT5vi.png" /></figure><p>On the detail page of your run you can see some more information to see what is happening per stage. You can even rerun stages if they failed or you want to rerun them with different environment variables.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*S2aVAaD71rpUrtXc.png" /></figure><h4>Configure build stage</h4><p>We still don’t have anything to deploy other than some echo scripts. <strong>It’s building time 👷🏻‍♂!</strong></p><p>Add the necessary steps to our yml file to build the Angular app. We will install NodeJS, install our project’s npm dependencies and eventually build and publish an optimized production version.</p><p>Change the <em>build</em> stage of our pipeline:</p><pre>stages:<br>  - stage: build<br>    jobs:<br>      - job:<br>        steps:<br>          - task: NodeTool@0<br>            inputs:<br>              versionSpec: &#39;10.x&#39;<br>          - script: npm install<br>          - script: npm run build -- --prod<br>          - publish: dist<br>            artifact: dist</pre><p>Commit your changes and let DevOps start a new pipeline run. After the run you can validate the output by checking the produced artifacts:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OCIh34YX4D2AKlvQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*NfwOxxW5RYj2FpTJ.png" /></figure><h4>Configure deployment stages</h4><p>Okay, we are now able to set up, configure and build an Angular application via Azure DevOps ✅👏. This is a great moment to grab yourself a coffee or beer, depending on what time it is 😉. Next stop: the deployment stages.</p><p>We are not going to deploy our application to a real server because that goes beyond the scope of this article. Let’s save that for a future article about deploying with ARM templates!</p><p>So, what was the actual topic of this article again🤔? When I started writing this article I wanted to focus primarily on handling environment specific settings in an Angular application with the environment.ts file. But why not add a real life example to it with some nice additions about Azure multi-stage yml releases too? So you can release your Angular application properly in Azure.</p><h3>Change to deployment jobs</h3><p>We are now going to change the yml file a bit to change our temporary deployment stages to real <a href="https://docs.microsoft.com/en-us/azure/devops/pipelines/yaml-schema?view=azure-devops&amp;tabs=schema%2Cparameter-schema#deployment-job">deployment jobs</a>.</p><blockquote>A deployment job is a special type of job. It’s a collection of steps to run sequentially against the environment. In YAML pipelines, we recommend that you put your deployment steps in a deployment job.</blockquote><pre>- stage: deploy_dev<br>  displayName: Deploy to development<br>  jobs:<br>    - deployment: DeployWeb<br>      environment: DEV<br>      strategy:<br>        runOnce:<br>          deploy:<br>            steps:<br>              - script: echo Hello, development world!<br><br>- stage: deploy_prd<br>  displayName: Deploy to production<br>  jobs:<br>    - deployment: DeployWeb<br>      environment: PRD<br>      strategy:<br>        runOnce:<br>          deploy:<br>            steps:<br>              - script: echo Hello, production world!</pre><p>Not much changes, just following the documentation from Microsoft. Thing that you will notice is the <em>environment</em> setting. This is, in our case, just a label to group our deployment and see the history of our deployments. It also gives you Approval configuration. More about that later. Check this <a href="https://docs.microsoft.com/en-us/azure/devops/pipelines/process/environments?view=azure-devops">link</a> to learn more about environments in DevOps.</p><p>You can now see your environments in the portal too:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IGrxe7q96jLUYVk2.png" /></figure><h3>Extend environment.ts</h3><p>So, now we are getting close to our actual end goal: handling environment specific variables in a Angular application via Azure multi-stage pipelines. At this moment our environment.ts and environment.prod.ts files don&#39;t contain anything environment specific. Let&#39;s add some dummy environment settings for the sake of this article. We pretend that we have an API that is environment specific and we&#39;re using Auth0 as our authentication provider.</p><pre><em>// environment.ts</em><br><strong>export</strong> <strong>const</strong> environment <strong>=</strong> {<br>  production: <strong>false</strong>,<br>  auth: {<br>    clientID: &#39;my-local-clientid&#39;,<br>    domain: &#39;local.eu.auth0.com&#39;,<br>  },<br>  apiEndpoint: &#39;https://local.myapi.io&#39;,<br>};</pre><pre><em>// environment.prod.ts</em><br><strong>export</strong> <strong>const</strong> environment <strong>=</strong> {<br>  production: <strong>true</strong>,<br>  auth: {<br>    clientID: &#39;#{authClientID}#&#39;,<br>    domain: &#39;#{authDomain}#&#39;,<br>  },<br>  apiEndpoint: &#39;#{apiEndpoint}#&#39;,<br>};</pre><p>Okay Kevin, I don’t think #{authClientID}# is a valid client id. You&#39;re completely right, of course 🙃. These are, so called, replacement tokens. And we&#39;re going to utilize them during our deployment stages to replace the tokens with the actual values. But first, don&#39;t forget to commit and push your changes.</p><h4>Use environment variables in your code</h4><p>If we do not use these variables in our code, tree shaking will remove the code from the build. So that would not be very useful for this tutorial. So add this line of code to your app.component.ts file:</p><pre>@Component({<br>  selector: &#39;app-root&#39;,<br>  templateUrl: &#39;./app.component.html&#39;,<br>  styleUrls: [&#39;./app.component.css&#39;],<br>})<br><strong>export</strong> <strong>class</strong> AppComponent {<br>  title <strong>=</strong> `is production: ${environment.production}, auth: ${environment.auth.clientID} - ${environment.auth.domain}, api: ${environment.apiEndpoint}`;<br>}</pre><h3>Add Azure DevOps extension</h3><p>We now know that we want these tokens to be replaced by the actual values. You could roll your own script to accomplish this, but we’re going to use an extension for this. This extension needs to be installed on organization level, so it could be possible that you need to request this extension to your organization owner. The extension we’re going to install is called <a href="https://marketplace.visualstudio.com/items?itemName=qetza.replacetokens&amp;ssr=false#qna">Replace Tokens</a> from <a href="https://twitter.com/grouchon">Guillaume Rouchon</a>.</p><h4>Add variable groups</h4><p>With our extension in place, it’s time to add the actual variables that will be used to substitute the tokens. Navigate to the <strong>Library</strong> section to create two variable groups that contain variables for our two environments: DEV and PRD.</p><ul><li>Variable groups overview</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5Ob7W9xmG_6eL2dQ.png" /></figure><ul><li>Add the variables for DEV</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bu_hf1aK8ifa4GJB.png" /></figure><ul><li>Add the variables for PRD (clone your previous variable group and replace values)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qSPgMR97wVydnOFT.png" /></figure><ul><li>Eventually, you should now have two groups</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*N85t3wjqtKijVYNk.png" /></figure><h4>Reference your variable groups in your pipeline</h4><p>We can now use these variables groups in our yml pipeline. Add the <em>variables</em> property to each deployment stage below the <em>displayname</em> property:</p><pre>- stage: deploy_dev<br>  displayName: Deploy to development<br>  variables:<br>    - group: DEV<br>  jobs:<br>    ...<br><br>  - stage: deploy_prd<br>    displayName: Deploy to production<br>    variables:<br>      - group: PRD<br>    jobs:<br>     ...</pre><h4>Add Replace token task</h4><ul><li>Extensions installed ✅</li><li>Variable groups created ✅</li><li>Variable groups referenced in yml ✅</li></ul><p>Now add the replace tokens extension as step to each deployment stage. Make sure you configure the value of <em>targetFiles</em> properly. What we’re doing here is changing all occurrences of our replacement tokens in the main*.js files. So that would include the main-es5.*.js and main-es2015.*.js file.</p><pre>- stage: deploy_dev<br>  displayName: Deploy to development<br>  variables:<br>    - group: DEV<br>  jobs:<br>    - deployment: deploy<br>      environment: DEV<br>      strategy:<br>        runOnce:<br>          deploy:<br>            steps:<br>              - script: echo Hello, development world!<br>              - task: replacetokens@3<br>                inputs:<br>                  targetFiles: &#39;$(Pipeline.Workspace)/dist/**/main*.js&#39;<br>                  encoding: &#39;auto&#39;<br>                  writeBOM: true<br>                  verbosity: &#39;detailed&#39;<br>                  actionOnMissing: &#39;warn&#39;<br>                  keepToken: false<br>                  tokenPrefix: &#39;#{&#39;<br>                  tokenSuffix: &#39;}#&#39;<br>                  useLegacyPattern: false<br>                  enableTelemetry: true<br><br>- stage: deploy_prd<br>  displayName: Deploy to production<br>  variables:<br>    - group: PRD<br>  jobs:<br>    - deployment: deploy<br>      environment: PRD<br>      strategy:<br>        runOnce:<br>          deploy:<br>            steps:<br>              - script: echo Hello, production world!<br>              - task: replacetokens@3<br>                inputs:<br>                  targetFiles: &#39;$(Pipeline.Workspace)/dist/**/main*.js&#39;<br>                  encoding: &#39;auto&#39;<br>                  writeBOM: true<br>                  verbosity: &#39;detailed&#39;<br>                  actionOnMissing: &#39;warn&#39;<br>                  keepToken: false<br>                  tokenPrefix: &#39;#{&#39;<br>                  tokenSuffix: &#39;}#&#39;<br>                  useLegacyPattern: false<br>                  enableTelemetry: true</pre><p>Now let’s run this pipeline by committing and pushing your changes 🚀!</p><p>Because we’re not deploying our code to a working environment, we can’t verify if the replacement action actually worked…What we can do is check the logging. So open the last run in the DevOps portal and click on the replacetokens job to see: <em>3 tokens replaced out of 3</em></p><ul><li>DEV</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*z-pfQQqEDkVw_6qf.png" /></figure><ul><li>PROD</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*d5qX_tKWcgfUbTL9.png" /></figure><h3>Bonus: add dependsOn and conditions</h3><p>As you can see, your pipeline will sequentially run all stages. But you want to make sure that your production deployment will only be executed in certain conditions. We can make use of dependsOn and conditions to restrict the execution a bit. Add these properties to your deployment stages:</p><pre>....<br>displayName: Deploy to development<br>dependsOn:<br>  - build<br>condition: and(succeeded(), eq(variables[&#39;Build.SourceBranch&#39;], &#39;refs/heads/master&#39;))<br>....</pre><pre>....<br>displayName: Deploy to production<br>dependsOn:<br>  - build<br>  - deploy_dev<br>condition: and(succeeded(), eq(variables[&#39;Build.SourceBranch&#39;], &#39;refs/heads/master&#39;))<br>....</pre><p>Our stages do now depend on the build and/or deploy_dev stage and so will only run when that stage succeeds. Also we introduced the condition that the git branch should be equal to master. This gives you a bit more control about your pipeline. You can even introduce manual intervention by configuring an Approval step on the specific environment:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ZxwEvRuCXKYvqc03.png" /></figure><h3>Conclusion</h3><p>Building and deploying Angular applications doesn’t need to be very complex if we’re talking about environments. I showed you how to utilize the Angular environment files properly in a Azure DevOps multi-stage yml release pipeline without the need to rebuild the application for every environment. And we did not introduce any extra start up complexity to our application. So no need to load our app configuration via the APP_INITIALIZER and delaying the actual start up of our web app. Just use the already provided environment files properly, environment.ts for local development and environment.prod.ts for production, and you&#39;re good to deploy with confidence!</p><p>What approach are you using at this moment?</p><p><em>Originally published at </em><a href="https://www.kevinboosten.dev/how-to-use-angular-environment-files-in-your-azure-devops-multi-stage-yml-release-pipeline"><em>https://www.kevinboosten.dev</em></a><em> on May 16, 2020.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f78d2af2b2e9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build and release your Ionic + Capacitor app via Microsoft App Center]]></title>
            <link>https://kevinboosten.medium.com/build-and-release-your-ionic-capacitor-app-via-microsoft-app-center-2493107c1ad6?source=rss-6a24c92e65b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/2493107c1ad6</guid>
            <category><![CDATA[ci-cd-pipeline]]></category>
            <category><![CDATA[appcenter]]></category>
            <category><![CDATA[mobile]]></category>
            <category><![CDATA[ionic]]></category>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[Kevin Boosten]]></dc:creator>
            <pubDate>Wed, 06 May 2020 00:00:00 GMT</pubDate>
            <atom:updated>2021-05-18T19:41:37.778Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*PcjQrqCAd14JZak-.png" /></figure><p>Building and deploying mobile applications can be challenging. I like developing mobile applications for iOS and Android. My framework of choice to do this is <a href="https://ionicframework.com/">Ionic</a>. Now Capacitor became the preferred way to access your native SDK’s in your hybrid app, building apps with App Center became a lot easier.</p><p>If you’re building a hybrid application with <a href="https://ionicframework.com/">Ionic</a>, you probably are using <a href="https://capacitor.ionicframework.com/">Capacitor</a> as your native bridge to get access to API’s like your camera, push notifications and others. If you’re not using it yet then you should definitely give it a try.</p><blockquote>Capacitor is a spiritual successor to Apache Cordova and Adobe PhoneGap, with inspiration from other popular cross-platform tools like React Native and Turbolinks, but focused entirely on enabling modern web apps to run on all major platforms with ease. Capacitor has backwards-compatible support for many existing Cordova plugins.</blockquote><p>Check out the <a href="https://capacitor.ionicframework.com/docs/">Capacitor docs</a> for a brief introduction and how to add capacitor to your application.</p><h3>App Center</h3><p>Visual Studio App Center is a Microsoft product for continuously build, test, release and monitor your apps. In this article we’re only going to focus on the building part of App Center. App Center supports a variety of operating systems: iOS, Android, Windows, MacOS and even tvOS. The platforms, besides the native ones, that are available are: React Native, Cordova (preview), Xamarin and Unity. Enough to cover your needs, I guess!</p><p>Before the introduction of Capacitor, it was not possible to build your Ionic + Cordova app with App Center. There is a Cordova (preview) feature but unfortunately it does not support building. Capacitor has a different philosophy than Cordova. With Capacitor you have full access to your iOS and Android projects and these will also be part of your git repository. Cordova generates these projects on every build, so you can not make changes without making use of the Cordova config.xml file.</p><h3>Ionic AppFlow</h3><p>Of course there are alternatives to build you mobile application. If you’re primarily building Ionic applications then <a href="https://ionicframework.com/appflow">Ionic AppFlow</a> will maybe be the better choice for you. They also have got ‘Publishing to Store’ functionality since a couple of months! So no need to manually download your artifacts from AppFlow and upload them to the stores anymore. But if you’re working in a company that also builds Xamarin and React Native apps and is also using Microsoft Azure, then App Center makes more sense.</p><h3>Create a test app</h3><blockquote><em>Skip this section if you already have an Ionic+Capacitor app</em></blockquote><p>So let’s start with creating a Ionic + Capacitor app so we can use that as our app that we’re going to use in App Center.</p><p>You can also fork this demo application from <a href="https://github.com/Boosten/ionic-capacitor-appcenter-demo">GitHub</a>.</p><p>First install the Ionic CLI</p><pre>npm install -g @ionic/cli</pre><p>Create an Angular application with Capacitor integration. At this point we just have a normal Angular web application, nothing special so far.</p><pre>ionic start myApp tabs --capacitor --type<strong>=</strong>angular<br>cd myApp</pre><p>Start the application to verify everything went well</p><pre>ionic serve</pre><p>Okay, you should now see a tabbed application with some dummy data in it.</p><p>Let’s add the native platforms to it. In order to do this, we should have at least build our application once, so run:</p><pre>ionic build</pre><p>Add the native platforms after that:</p><pre>npx cap add ios<br>npx cap add android</pre><p>Push your changes to a (private) repository and you are good to go!</p><h3>Configuring App Center</h3><p>We’re now going to create an app in App Center and connect it to our repository.</p><ol><li>Go to App Center to create a new application: <a href="https://appcenter.ms/apps">https://appcenter.ms/apps</a></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mBVqkQFMhdcYLrsA.png" /></figure><p>2. Enter a name for your application, select iOS en choose a release type. The release type is just a label and it does not have any affect on your build.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4mKLhhSvs_6CUjZl.png" /></figure><p>3. Select <strong>Build</strong> from the side-menu and connect your git repo.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*na-mJMghRqK5-6Kw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lGimf51VfJFnejGC.png" /></figure><p>4. Now click on the branch that you would like to configure for building (or click on the wrench icon). And click on <strong>Configure build</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*41W0MSi8f7zJ_7vm.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*QCzz4s10L4ns4OCP.png" /></figure><p>5. It’s possible that you see the error <em>You must add a shared scheme</em>. Follow the instructions in the link to set your workspace scheme to “Shared”. Also add the necessary Provisioning Profile and Certificate to build a valid.ipa file.</p><p><em>In case you forked the demo repo, you need to change the Team ID and App ID in Xcode manually and push these changes to your fork. Also provide a provisioning profile and certificate that matches your app. You don’t need to have paid developer account to create a valid provisioning profile, just export the certificate and profile from your machine that you use in Xcode.</em> Still having trouble? Maybe this can help you: <a href="https://intercom.help/appcenter/en/articles/1617765-ios-signing-issues-explained">iOS signing issues explained</a></p><p>You can also change other settings like building on each push and auto incrementing your build number.</p><p>Now click on <strong>Save &amp; Build</strong> to see what happens!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CVUZpJMFzYbUpLuT.png" /></figure><p>6. ❌ Aiiii, that escalated quickly! What happened? Remember we are trying to build a hybrid application? So what did we do to actually build the web part of the app?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zBDPbge-eJHNWlIs.png" /></figure><p>7. And here comes the ‘trick’ 💡! App Center supports several build scripts that run at pre-defined stages: post-clone, pre-build and post-build. That&#39;s exactly what we need to build our hybrid application with App Center. We&#39;re going to use the post-clone script in order to perform some steps that are required to build our app. Let&#39;s add a file appcenter-post-clone.sh to the iOS ( <em>ios/App/appcenter-post-clone.sh</em>) and Android ( <em>android/app/appcenter-post-clone.sh</em>) projects.</p><pre><em>#!/usr/bin/env bash</em><br><br><em># fail if any command fails</em><br>set -e<br><em># debug log</em><br>set -x<br><br><em># Required nodeJS version</em><br>NODE_VERSION<strong>=</strong>10.17.0<br><br><em># workaround to override the v8 alias</em><br>npm config delete prefix<br>. ~/.bashrc<br>nvm install &quot;$NODE_VERSION&quot;<br>nvm alias node10 &quot;$NODE_VERSION&quot;<br><br><em># go to root of project</em><br>cd ../..<br><br><em># install dependencies</em><br>npm i<br><br><em># run optimized production build</em><br>npm run build -- --prod<br><br><em># copy the web assets to the native projects and updates the native plugins and dependencies based in package.json</em><br>npx cap sync</pre><p>The first couple of lines are just to override the default NodeJS version that App Center is using. After that, we’re installing our npm dependencies, running an production build and finally invoking a Capacitor specific command to sync our web part of the application to the native projects.</p><p>Go back to the configuration and be sure to click on “Save &amp; Build” button to let App Center know that new build specific files need to be indexed.</p><p>Your build should now succeed after waiting for a couple of minutes 🎉.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Zsk77kJ_qiuZaMaY.png" /></figure><h3>Conclusion</h3><p>So, long story short: add the appcenter-post-clone.sh script to both native projects in your Ionic + Capacitor project, and you will be able to use App Center as your CI/CD platform.</p><p>You obviously can extend this script with all the things you need. For example: you could change the dev/prod mode based on an environment variable that you can set in your App Center build configuration. Definitely take a look at the <a href="https://github.com/microsoft/appcenter/tree/master/sample-build-scripts">Microsoft sample-build-scripts repo</a>.</p><h3>Next steps?</h3><ul><li>Extend your build configuration to your needs</li><li>Distribute builds to distribution groups</li><li>Publish your application to the public stores</li></ul><p>In my next blog I will describe how to properly distribute your app for testing purposes and how to add new test devices to your apps provisioning profile for your iOS distribution.</p><p>Stay tuned and happy building 🏗👷🏻‍♂️👷🏻‍♀️!</p><p><em>Originally published at </em><a href="https://www.kevinboosten.dev/release-your-ionic-and-capacitor-app-via-appcenter"><em>https://www.kevinboosten.dev</em></a><em> on May 6, 2020.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2493107c1ad6" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>