Codementor Events

Application Setup: Laravel 5 & Angular 2

Published Mar 28, 2017
Application Setup: Laravel 5 & Angular 2

Following the tutorial that I wrote on AngularJS & ASP.NET MVC5, I want to introduce a simple tutorial that’s useful to setting up a new application using Laravel 5.2 and Angular 2 with the asset pipeline offered by Laravel.’

We are going to setup the 5 mins quickstart, from Angular 2 Beta into a Laravel view. We will use the Laravel Elixir to create a basic gulp task, that compiles the Typescript Angular code and to move some files.

Let’s start! To begin, after creating the basic Laravel application, we need to gather all the sources needed to run Angular 2 Beta and the Typescript compiler. In the main folder of the newly created application, you can find a package.json file. Modify it by adding some dependencies as shown below:

{
  "private": true,
  "devDependencies": {
    "concurrently": "^1.0.0",
    "del": "^2.2.0",
    "gulp": "^3.8.8"
  },
  "dependencies": {
    "angular2": "2.0.0-beta.0",
    "bootstrap-sass": "^3.0.0",
    "elixir-typescript": "^1.1.2",
    "es6-promise": "^3.0.2",
    "es6-shim": "^0.33.3",
    "laravel-elixir": "^4.0.0",
    "reflect-metadata": "0.1.2",
    "rxjs": "5.0.0-beta.0",
    "systemjs": "0.19.6",
    "zone.js": "0.5.10"
  }
}
 

Now, type ‘npm install’ in the console and all the required files will be downloaded to the node_modules folder. As you can see, we added the requirements specified in the Angular site plus elixir-typescript — it is a simple Elixir task that compiles Typescript.

Once the installation is done, we can add the Typescript folder in the Laravel resource folder. Into this directory, we will create the two files app.component.ts and boot.ts. Both file content is shown below (same as the ones shown on the Angular Beta 5 mins quickstart):

import {Component} from 'angular2/core';
 
@Component({
    selector: 'my-app',
    template: '<h1>My First Angular 2 App</h1>'
})
export class AppComponent { }
import {bootstrap}    from 'angular2/platform/browser'
import {AppComponent} from './app.component'
 
bootstrap(AppComponent);

As said before, we need to write a simple Elixir task to compile the Typescript. In the main folder of the application, locate the gulpfile.js, open it and paste the code below inside.

var elixir = require('laravel-elixir');
 
var elixirTypscript = require('elixir-typescript');
 
elixir(function(mix) {
    mix.sass('app.scss');
 
    mix.copy('node_modules/angular2', 'public/angular2');
    mix.copy('node_modules/rxjs', 'public/rxjs');
    mix.copy('node_modules/systemjs', 'public/systemjs');
    mix.copy('node_modules/es6-promise', 'public/es6-promise');
    mix.copy('node_modules/es6-shim', 'public/es6-shim');
    mix.copy('node_modules/zone.js', 'public/zone.js');
 
    mix.typescript('app.js','public/','/**/*.ts',{
                  "target": "ES5",
                  "module": "system",
                  "moduleResolution": "node",
                  "sourceMap": true,
                  "emitDecoratorMetadata": true,
                  "experimentalDecorators": true,
                  "removeComments": false,
                  "noImplicitAny": false,
    });
 
 
});

There are two important things in the gulpfile:
We have copied the tsconfig option from the 5mins tutorial and inputted into the Elixir Typescript plugin
We have a little problem to solve: the plugin concatenates all the JavaScript compiled files into a single app.js file. To avoid this behaviour, we have to make a little modification to the node module we downloaded.

In the node_modules folder, locate the elixir_typescript folder and within, the index.js file. In the return function, we have to comment on the concatenation pipe.

  new Task(pluginName, function () {
       var tsResult = gulp.src(assetPath + search)
           .pipe(ts(options, undefined, _laravelReporter.ElixirMessage()));
       return tsResult
           //  .pipe(concat(outputFileName))
             .pipe(gulp.dest(outputFolder));


   })


Now, if you run gulp from the command line you will see a newly created Typescript folder in the public directory and also, all the required dependencies copied to the same place. If all is working until now, we can end the setup by placing the Angular 2 application inside the Laravel welcome view, and start it using systemJS, nothing more than what is shown on the Angular site.

In the resource/view folder, open the welcome.blade.php file and paste the code below into it (I’ve omitted the style tag ).

 
<!DOCTYPE html>
<html>
    <head>
        <title>Laravel</title>
 
        <link href="https://fonts.googleapis.com/css?family=Lato:100" rel="stylesheet" type="text/css">
        <!-- 1. Load libraries -->
 
 <script src="es6-shim/es6-shim.min.js"></script>
 <script src="/systemjs/dist/system-polyfills.js"></script>
 
  <script src="angular2/bundles/angular2-polyfills.js"></script>
  <script src="systemjs/dist/system.src.js"></script>
  <script src="rxjs/bundles/Rx.js"></script>
  <script src="angular2/bundles/angular2.dev.js"></script>
 
  <!-- 2. Configure SystemJS -->
  <script>
    System.config({
      "defaultJSExtensions": true,
      packages: {
        app: {
          format: 'register',
          defaultExtension: 'js'
        }
      }
    });
 
 
    System.import('app/boot')
          .then(null, console.error.bind(console));
  </script>
    </head>
    <body>
        <div class="container">
            <div class="content">
                <div class="title">Laravel 5</div>
                <my-app>Loading...</my-app>
            </div>
        </div>
    </body>
</html>
 

That’s all! Now, if you visit the application home page, you will see under the Laravel 5 title, the running Angular 2 application. This short tutorial shows how to setup your first application using Laravel and Angular2. Some things need to be refined, like the JavaScript destination folder, and the need to copy the node_modules to the public folder, but it’s a good starting point. It allows two of the best web application frameworks to work together in one place. In the video below, you can see this tutorial, and you can find all the codes on GitHub.

Here is the video:
Laravel With Angular 2

Check out the codes for this tutorial in my GitHub Repo

Discover and read more posts from Syed Ikram Shah
get started
post comments4Replies
Charles Jackson
7 years ago

You should remove this article.

For starters; you cannot modify anything inside the node_modules folder, it is not designed to be under revision control and any changes will be overwritten by a deployment solution

Secondly, try installing Angular in a totally separate domain/container and avoid all the hassle. It is a decoupled solution.

Sorry for being blunt but this solution is seriously misguided.

aman gupta
7 years ago

Hi, i am building a project in laravel 5.5 or angular 4. Can you tell me what is best way that both can work together. I have to create two folder one for angular and other for laravel then angular request for data in laravel and laravel response as API. I think laravel work as API. Can you tell me best way for it.

toni-rmc
7 years ago

Here is my approach:

https://github.com/toni-rmc/laravel-angular-integration

You might want to check it out.

  • no need for you to edit anything in the node_modules
  • has a built in watch mode support
  • integrating multiple Angular applications in Laravel is just as easy as integrating one
  • complete separation of TypeScript code from transpiled JavaScript code
  • all of the Angular apps are kept completely separate from the rest of the Laravel project in their own directory
Cosette Malinowski
7 years ago

It’s great to see more people writing about Angular 2, there’s still very little documentation out there!
Speaking of which, if you need a tool to handle the localization of Angular 2 apps, you can check out the localization management platform https://poeditor.com
It supports xmb and xtb files.

Show more replies