<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>vue &#8211; blog.boro2g .co.uk</title>
	<atom:link href="https://blog.boro2g.co.uk/tag/vue/feed/" rel="self" type="application/rss+xml" />
	<link>https://blog.boro2g.co.uk</link>
	<description>Some ideas about coding, dev and all things online.</description>
	<lastBuildDate>Mon, 04 Feb 2019 11:39:38 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.5.8</generator>
	<item>
		<title>Setting up JSS with Vue, Typescript and dependency injection</title>
		<link>https://blog.boro2g.co.uk/setting-up-jss-with-vue-typescript-and-dependency-injection/</link>
					<comments>https://blog.boro2g.co.uk/setting-up-jss-with-vue-typescript-and-dependency-injection/#respond</comments>
		
		<dc:creator><![CDATA[boro]]></dc:creator>
		<pubDate>Mon, 04 Feb 2019 11:23:03 +0000</pubDate>
				<category><![CDATA[Sitecore]]></category>
		<category><![CDATA[jss]]></category>
		<category><![CDATA[sitecore]]></category>
		<category><![CDATA[typescript]]></category>
		<category><![CDATA[vue]]></category>
		<guid isPermaLink="false">https://blog.boro2g.co.uk/?p=991</guid>

					<description><![CDATA[<p>If JSS is a new term for you, I&#8217;d seriously recommend checking our the documentation that Sitecore have provided: https://jss.sitecore.com/ . By the end of this post we&#8217;ll have run through how you can get JSS up and running locally, with dependencies all wired together using a DI container and any functional aspects written in [&#8230;]</p>
<p>The post <a rel="nofollow" href="https://blog.boro2g.co.uk/setting-up-jss-with-vue-typescript-and-dependency-injection/">Setting up JSS with Vue, Typescript and dependency injection</a> appeared first on <a rel="nofollow" href="https://blog.boro2g.co.uk">blog.boro2g .co.uk</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>If JSS is a new term for you, I&#8217;d seriously recommend checking our the documentation that Sitecore have provided: <a rel="noreferrer noopener" aria-label="https://jss.sitecore.com/ (opens in a new tab)" href="https://jss.sitecore.com/" target="_blank">https://jss.sitecore.com/</a> . </p>



<p>By the end of this post we&#8217;ll have run through how you can get JSS up and running locally, with dependencies all wired together using a DI container and any functional aspects written in TypeScript. For us this is a key set of requirements &#8211; we&#8217;ve worked with many projects that have grown over several years. By putting in some key rules and requirements up front should mean with good discipline that the codebase can scale over time.</p>



<p><strong>Why&nbsp;JSS?</strong></p>



<p>Imagine a standard Sitecore development team, typically based around C# developers and some front end devs. In the default approach to building a site you&#8217;d need everyone to contribute Razor files with the markup and associated styling and functionality. This is the approach you would probably have seen for several years until more recently with the demand for richer front end technologies. Think Vue, Angular, React and so on. </p>



<p>This is what JSS facilitates.</p>



<p><strong>Is this right for everyone?</strong></p>



<p>Just because technologies exist, it doesn&#8217;t always make them the right platform to jump on. E.g. if you have a very established Sitecore development team that doesn&#8217;t have the appetite for these front end technologies, then JSS might not be the thing for you.</p>



<p><strong>Getting started</strong></p>



<p>The quick start from the docs site provides 4 tasks to get you started:</p>



<pre class="crayon-plain-tag">npm install -g @sitecore-jss/sitecore-jss-cli
jss create my-first-jss-app vue
cd my-first-jss-app
jss start</pre>



<p>Provided you have node installed, once you run ^ you should then see <a href="http://localhost:3000" target="_blank" rel="noreferrer noopener" aria-label="http://localhost:3000 (opens in a new tab)">http://localhost:3000</a> fire up.</p>



<p><strong>Why TypeScript?</strong></p>



<p>I wouldn&#8217;t consider starting a new web project now without TypeScript as it provides so many useful features for a codebase. Refactoring is just like if you were using C#, variables have types, classes can implement other abstract classes or interfaces. If you&#8217;ve not used it before, I&#8217;d highly recommend it.</p>



<p>In terms of designing your application, another key factor to consider is the coupling between the different layers. Core functionality being one layer, your UI framework being another. If you structure things so that e.g. you can peel out Vue without too much trouble, moving up through different technologies or versions will be a breeze.</p>



<p><strong>Changes to the default app</strong></p>



<p>Here we&#8217;ll add things like some demo services, some DI registrations and a few other bits we&#8217;ll need.</p>



<p>1.First up lets include some extra dependencies:</p>



<pre class="crayon-plain-tag">npm install -d inversify-inject-decorators, vue-class-component, inversify, vue-property-decorator, reflect-metadata, ts-loader, typescript</pre>



<p>2. In src/AppRoot.vue, before the <code>export default</code> line add <code>import "reflect-metadata"</code><br></p>



<p>3. Add a tsconfig.json file to the root folder (a level above src):</p>



<pre class="crayon-plain-tag">{
    &quot;compilerOptions&quot;: {
        &quot;outDir&quot;: &quot;./built/&quot;,
        &quot;sourceMap&quot;: true,
        &quot;strict&quot;: true,
        &quot;module&quot;: &quot;es2015&quot;,
        &quot;moduleResolution&quot;: &quot;node&quot;,
        &quot;target&quot;: &quot;es5&quot;,       
        &quot;lib&quot;: [
            &quot;es6&quot;,
            &quot;dom&quot;
        ],
        &quot;types&quot;: [
            &quot;reflect-metadata&quot;
        ],
        &quot;experimentalDecorators&quot;: true,
        &quot;emitDecoratorMetadata&quot;: true,
        &quot;baseUrl&quot;: &quot;./src&quot;,
        &quot;paths&quot;: {            
            &quot;@di_ids&quot;: [&quot;DependencyInjection/Identifiers&quot;]
        }
    },
    &quot;include&quot;: [
        &quot;./src/**/*&quot;
    ]
}</pre>



<p>4. Update the webpack config, in the Vue world this is done in <code>vue.config.js</code></p>



<pre class="crayon-plain-tag">//at the top of the file:
let path= require('path');

//alongside the graphql includes:
config.module.rules.push({
    test: /\.tsx?$/,
    loader: 'ts-loader',
    exclude: /node_modules/,
    options: {
      appendTsSuffixTo: [/\.vue$/],
    }
  });

config.resolve.extensions.push('.ts');

//note, this is required for alias'ing to work for your references - a nice way to avoid crazy import statements. Same change exists in tsconfig

config.resolve.alias[&quot;@di_ids&quot;] = path.resolve(__dirname, 'src/DependencyInjection/Identifiers')</pre>



<p>5. Now add a <code>vue-shim.d.ts</code> (in the src folder)</p>



<pre class="crayon-plain-tag">declare module &quot;*.vue&quot; {
    import Vue from &quot;vue&quot;;
    export default Vue;
}</pre>



<p>6. Next, some dummy TypeScript dependencies:</p>



<pre class="crayon-plain-tag">// /src/scripts/processors/TestProcessor.ts

import { IService } from &quot;../services/TestService&quot;;
import { inject, injectable } from 'inversify';
import {SERVICE_IDENTIFIER} from &quot;@di_ids&quot;;

@injectable()
export default class TestProcessor
{    
    constructor(@inject(SERVICE_IDENTIFIER.IService) private service:IService) {        
        
    }

    public DoSomething() : string {
        return this.service.DoIt();
    }
}

// /src/scripts/services/TestServices.ts

import { injectable } from 'inversify';

@injectable()
export class ServiceA implements IService {
    DoIt(): string {
        return &quot;ServiceA&quot;;
    }

}
@injectable()
export class ServiceB implements IService {
    DoIt(): string {
        return &quot;ServiceB&quot;;
    }

}

export interface IService {
    DoIt(): string;
}</pre>



<p>7. And the DI  container and keys:</p>



<pre class="crayon-plain-tag">// /src/DependencyInjection/ContainerRoot.ts

import { Container } from &quot;inversify&quot;;
import getDecorators from 'inversify-inject-decorators';
import TestModule from './Modules/TestModule'

let container = new Container();

container.load(TestModule);

const { lazyInject } = getDecorators(container);

export { container, lazyInject }

// /src/DependencyInjection/Identifiers.ts

const SERVICE_IDENTIFIER = {
    IService: Symbol(&quot;IService&quot;),
    Container: Symbol(&quot;Container&quot;),
    TestProcessor: Symbol(&quot;TestProcessor&quot;)
};

export {SERVICE_IDENTIFIER}

// /src/DependencyInjection/Modules/TestModule.ts

import { ContainerModule, interfaces } from &quot;inversify&quot;;
import { SERVICE_IDENTIFIER } from &quot;../Identifiers&quot;;
import { IService, ServiceA, ServiceB } from &quot;../../scripts/services/TestService&quot;;
import TestProcessor from &quot;../../scripts/processors/TestProcessor&quot;;

const testServices = new ContainerModule(
    (
        bind: interfaces.Bind
    ) =&gt; {
        bind&lt;IService&gt;(SERVICE_IDENTIFIER.IService).to(ServiceA);
        bind&lt;TestProcessor&gt;(SERVICE_IDENTIFIER.TestProcessor).to(TestProcessor);
    }
);

export default testServices;</pre>



<p>8. Now a TypeScript enabled Vue component: <code>/src/components/Hello.vue</code></p>



<pre class="crayon-plain-tag">&lt;template&gt;
    &lt;div&gt;
        &lt;div class=&quot;greeting&quot;&gt;Hello {{name}}{{exclamationMarks}}&lt;/div&gt;
        &lt;button @click=&quot;decrement&quot;&gt;-&lt;/button&gt;
        &lt;button @click=&quot;increment&quot;&gt;+&lt;/button&gt;       
    &lt;/div&gt;
&lt;/template&gt;

&lt;script lang=&quot;ts&quot;&gt;
import { Vue, Component, Prop, Inject } from 'vue-property-decorator'
import { Container } from &quot;inversify&quot;;
import TestProcessor from '../scripts/processors/TestProcessor';
import { SERVICE_IDENTIFIER } from &quot;@di_ids&quot;;
import { inject, injectable } from 'inversify';
import { lazyInject } from '../DependencyInjection/ContainerRoot';


@Component({
    //components: { SubComponent }
})
export default class Hello extends Vue
{      
    @lazyInject(SERVICE_IDENTIFIER.TestProcessor)
    private _testProcessor!: TestProcessor;

// // If you want to use Vue's OTB Inject/Provide you can
    // @Inject(SERVICE_IDENTIFIER.Container)
    // private _container!: Container;

    created (): void {
        //console.log(this._container.resolve&lt;TestProcessor&gt;(TestProcessor).DoSomething());

        console.log(this._testProcessor.DoSomething());
    }

    @Prop() name!: string;
    @Prop() initialEnthusiasm!: number;    

    enthusiasm = this.initialEnthusiasm;

    increment() {
        this.enthusiasm++;
    }
    decrement() {
        if (this.enthusiasm &gt; 1) {
            this.enthusiasm--;
        }
    }

    get exclamationMarks(): string {
        return Array(this.enthusiasm + 1).join('!');
    }    
}
&lt;/script&gt;

&lt;style&gt;
.greeting {
    font-size: 20px;
}
&lt;/style&gt;</pre>



<p>9. And to finally get it showing on a page, edit layout.vue to include your component:</p>



<pre class="crayon-plain-tag">&lt;div class=&quot;container&quot;&gt;
      &lt;!-- &lt;placeholder name=&quot;jss-main&quot; :rendering=&quot;route&quot; /&gt; --&gt;
      &lt;Hello :initialEnthusiasm=&quot;5&quot; /&gt;
&lt;/div&gt;

//...
import Hello from './components/Hello'

//...
components: {
    //...,
    Hello
},</pre>



<p>After all that, you should see the homepage load up and &#8220;ServiceA&#8221; getting logged to the console. Not the most impressive output but shows the full flow of dependencies getting configured and resolved, with all the code written in TypeScript <img src="https://s.w.org/images/core/emoji/15.0.3/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>



<p>If you are using SSR Renderings, you&#8217;ll also need to add <code>|ts</code> into the list of rules that get &#8216;unshift&#8217;ed in <code>/server/server.vue.config.js</code></p>
<p>The post <a rel="nofollow" href="https://blog.boro2g.co.uk/setting-up-jss-with-vue-typescript-and-dependency-injection/">Setting up JSS with Vue, Typescript and dependency injection</a> appeared first on <a rel="nofollow" href="https://blog.boro2g.co.uk">blog.boro2g .co.uk</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.boro2g.co.uk/setting-up-jss-with-vue-typescript-and-dependency-injection/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
