Latest news about Bitcoin and all cryptocurrencies. Your daily crypto news habit.
The purpose of this guide is to have a working Docker setup with Angular CLI while using Pug. I had some problems while getting the three of them to work together.Iâm going to assume you know a little bit of Docker (Although itâs not necessary) to keep it working.
Hereâs the GitHub repo with the finalized code.
Some Notes:
- This guide works for existing and new Angular-CLI applications.
- You must have NodeJS 8+, Docker v18+ (Not necessarily, you can change the compose version to a lower number) already installed.
- Iâm currently using Windows 10 with Ubuntu installed. Itâs important to note this because node-sass is going to give you problems when you try to run it with node_modules (Only happens with Windows)
- The pug image was taken from user Mamugi1492 at RedBubble
Step #1âââCreating the new Angular Project
Skip this step, and go to #3 if you have an existing project that you want to Dockerize.
If youâre running Windows, and you will start fresh, skip to step #2. Others (Mac/Linux), do the following:
npm install -g @angular/cli
ng new angular-pug-sass-docker-app --style=scss
This will install the angular cli globally, and then create a new angular app with Sass. Change angular-pug-sass to your projectâs name.
Step #2âââWindows Only
On Windows, if you create an app with the CLI, Node-Sass automatically sets itself up with said OS in mind. When you use Docker, you will run it via a Linux image. Once you mount the directory (so we can edit without rebuilding), it references the node_modules directory which has the node-sass installed with Windows.
You can either delete node_modules . Or, force rebuild node-sass. Unfortunately, I was not able to get it to work with any of these methods. Thatâs why I recommend you to follow option #1, and leave option #2 as an alternative.
Option #1âââCreate the New Angular Project within Windowsâs Linux distro (Recommended)
You will need to install Ubuntu on Windows 10 (Or any Linux version) https://docs.microsoft.com/en-us/windows/wsl/install-win10. You probably have it, since you mustâve installed Docker.
Open the Ubuntu Terminal and go to the directory you want to create the new app. In my case, Iâm going to specify it in the desktop:
We do this by mounting the C drive (/mnt/c) and navigating to my desktop location C:\Users\jjancp\Desktop.
Combining both, we have:
cd /mnt/c/Users/jjancp/Desktop
Global install the cli:
sudo npm install -g @angular/cli
Create the new angular project:
ng new angular-pug-sass-docker-app --style=scss
Option #2- Create the New Angular Project within Windows and then use npm rebuild node-sass
This method didnât work for me. In here, you install your modules directly from Windows, as any common project:
Globally installing the angular-cli in PowerShell or CMD:
npm install -g @angular/cli
Then, create the new Angular Project:
ng new angular-pug-sass-docker-app --style=scss
Step #3âââAdd the ng-cli-pug-loader
Read this article from Mark Pieszak (Optional), about the ng-cli-pug-loader.
ng add ng-cli-pug-loader
This command will install all the packages from package.json and add a file called ng-add-pug-loader.js at the projectâs root, it will add pug-loader, pug, and apply-loader to the devDependencies. Finally, itâs going to include a run command in the package.jsonâs postinstall .
What this does, as explained in the linked article above, is that it edits the Webpack Config file from Angular, and injects the Pug loader to it, without the need to eject the Angular app!.
Something important: We do this manually, without specifying a docker image because we will not need to run ng add again. I was personally having problems when I tried to automate with Docker the whole process.
Step #4âââ[ERR_INVALID_CALLBACK]: Callback must be a function in ng-add-pug-loader.js
You may come up with this problem. I still donât know whatâs the cause of the problem. But changing all the fs methods to synchronous seem to fix the following error:
TypeError [ERR_INVALID_CALLBACK]: Callback must be a function at maybeCallback (fs.js:133:9) at Object.writeFile (fs.js:1139:14) at fs.readFile (/usr/app/ng-add-pug-loader.js:20:6) at FSReqWrap.readFileAfterClose [as oncomplete] (internal/fs/read_file_context.js:53:3)error Command failed with exit code 1.
A quick and dirty solution is to edit the ng-add-pug-loader.js. So go and open the file:
- Change Line 9 to fs.readFileSync
- Line 20 to fs.writeFileSync
- Line 21 to fs.closeSync
Hereâs the file ( I created an issue in the repo):
/**
* Adds the pug-loader inside Angular CLI's webpack config, if not there yet.* @see https://github.com/danguilherme/ng-cli-pug-loader*/
const fs = require('fs');
const commonCliConfig = 'node_modules/@angular-devkit/build-angular/src/angular-cli-files/models/webpack-configs/common.js';
const pugRule = '{ test: /.pug$/, use: [ { loader: "apply-loader" }, { loader: "pug-loader" } ] },';
fs.readFileSync(commonCliConfig, (err, data) => {
if (err) { throw err; }
const configText = data.toString();
// make sure we don't add the rule if it already exists if (configText.indexOf(pugRule) > -1) { return; } // Insert the pug webpack rule
const position = configText.indexOf('rules: [') + 8; const output = [configText.slice(0, position), pugRule, configText.slice(position)].join('');
const file = fs.openSync(commonCliConfig, 'r+');
fs.writeFileSync(file, output);
fs.closeSync(file);
});
Step #5âââThe Dockerfile
# Installs the current application on a Node Image.FROM node:10.5
# The qq is for silent output in the console# You are welcome to modify this part as itRUN apt-get update -qq && apt-get install -y build-essential libpq-dev vim
# Sets the path where the app is going to be installedENV NODE_ROOT /usr/app/
# Creates the directory and all the parents (if they donât exist)RUN mkdir -p $NODE_ROOT
# Sets the /usr/app as the active directoryWORKDIR $NODE_ROOT
# Copies all the content
COPY . .
# Install all the packagesRUN yarn install
RUN npm install -g @angular/cli
# Uncomment this if you went with Option #2 in Step #2 (Windows Only)# RUN npm rebuild node-sass --force
# The default port from ng serve (4200)# and 49153 for Webpack Hot Module ReloadEXPOSE 4200 49153
Create an extensionless file, called Dockerfile and add it to the projectâs root. Copy the contents above. If youâre experienced with Docker, you may see that weâre copying the whole folder, and then running the install. We can opt to copy the ng-add-pug-loader, angular.json, and the package.json files and run yarn install. I found some problems (could be due to my setup) to get it working.
If you decided to go with Step #2 Option #2 (Windows only). Itâs likely that youâre going to have node-sass issues. Try seeing if the rebuild works. I tried it, and it didnât.
If youâre having problems with the image, go to the Appendix at the bottom.
.dockerignore
.dockerignore./log./tmppackage.lock.json.git*Dockerfile**docker-compose*node_modules
Create a nameless file with extension .dockerignore and copy the contents above.
Step #6âââCreate the docker-compose.yml file
Create a docker-compose.yml file in the root of the project, add the following:
version: â3.6âservices: app: build: . command: ânpm startâ ports: - â4200:4200â - "49153:49153" expose: - â4200â - "49153" volumes: - â./:/usr/app/â
The volumes key will map our current directory to the Docker imageâs content. This way, we donât need to reload the container to see the changes.
If you check the npm start from the docker-compose youâll see that itâs going to run ng serve . We need to make a slight adjustment inside the package.json
Step #7âââUpdate the package.json
For it to be correctly exposed to the outside world, we need to go to the start script and modify it. In addition, we need to add a polling mechanism so Angular CLI can pick up the changes within the container:
From:
âstartâ: âng serveâ,
To:
âstartâ: âng serve --host 0.0.0.0 --poll=500â,
This command will let you navigate via http://localhost:4200
Example for the ng start script
The polling mechanism is measured in milliseconds. You can tune this to your preference.
Step #8â Change .html to .pug
Do not change the main index.html to .pug. The loader will not parse it.
Update app.component.html to app.component.pug Update its content:
div(style='text-align:center') h1 | Welcome to {{ title }}! img(width='300', alt='Angular Logo', src='data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAyNTAgMjUwIj4KICAgIDxwYXRoIGZpbGw9IiNERDAwMzEiIGQ9Ik0xMjUgMzBMMzEuOSA2My4ybDE0LjIgMTIzLjFMMTI1IDIzMGw3OC45LTQzLjcgMTQuMi0xMjMuMXoiIC8+CiAgICA8cGF0aCBmaWxsPSIjQzMwMDJGIiBkPSJNMTI1IDMwdjIyLjItLjFWMjMwbDc4LjktNDMuNyAxNC4yLTEyMy4xTDEyNSAzMHoiIC8+CiAgICA8cGF0aCAgZmlsbD0iI0ZGRkZGRiIgZD0iTTEyNSA1Mi4xTDY2LjggMTgyLjZoMjEuN2wxMS43LTI5LjJoNDkuNGwxMS43IDI5LjJIMTgzTDEyNSA1Mi4xem0xNyA4My4zaC0zNGwxNy00MC45IDE3IDQwLjl6IiAvPgogIDwvc3ZnPg==')
h2 Here are some links to help you start: ul li h2 a(target='_blank', rel='noopener', href='https://angular.io/tutorial') Tour of Heroes
li h2 a(target='_blank', rel='noopener', href='https://github.com/angular/angular-cli/wiki') CLI Documentation li h2 a(target='_blank', rel='noopener', href='https://blog.angular.io/') Angular blog
Update app.component.ts
Change:
templateUrl: â./app.component.htmlâ,
To:
templateUrl: â./app.component.pugâ,
This is how it will look:
import { Component } from '@angular/core';
@Component({ selector: 'app-root', templateUrl: './app.component.pug', styleUrls: ['./app.component.scss']})export class AppComponent { title = 'app';}
Step #9âââRun the app
Navigate to the folderâs project and run:
docker-compose up
All set đđđđđđđđđđ
Appendix A
If youâre running Windows and had an existing Angular app with the CLI and youâre having issues while Dockerizing the app, the solution is going to be to use Option #1 in Step #2.
- Remove the node_modules folder.
- Install Ubuntu on Windows 10, or Vagrant on Windows 7/8.x
- Open the Ubuntu Command, and map it to your installation. In the case of Ubuntu on Windows 10, do it like this:
cd /mnt/c/Users/MyUser/Path/To/Angular-Project
4. In Ubuntu: Install NodeJS.
5. Perform a yarn install or npm install
Appendix BâââSecurity Vulnerability (As of this writingâââJune 27, 2018) in one of the dependencies.
There seems to be an old dependency that the angular-cli uses (And NodeSass) that GitHub is alerting of a security vulnerability. Investigating further the issue, it seems that is an old Hoek version from Hapi. We do not have control of this, as it gets pulled automatically from the dependencies.
These seem to be the issues that address these problems:
Using Docker, Docker Compose, Angular-CLI 6+, Sass, and Pug (Jade) was originally published in Hacker Noon on Medium, where people are continuing the conversation by highlighting and responding to this story.
Disclaimer
The views and opinions expressed in this article are solely those of the authors and do not reflect the views of Bitcoin Insider. Every investment and trading move involves risk - this is especially true for cryptocurrencies given their volatility. We strongly advise our readers to conduct their own research when making a decision.