Skip to content

Commit

Permalink
fix(stark-demo): add baseHref dynamically via Angular provider to fix…
Browse files Browse the repository at this point in the history
… Showcase when published in GitHub pages

ISSUES CLOSED: #466
  • Loading branch information
christophercr committed Jun 29, 2018
1 parent e823761 commit 8dc6e8e
Show file tree
Hide file tree
Showing 3 changed files with 142 additions and 8 deletions.
35 changes: 27 additions & 8 deletions packages/stark-build/config/build-utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,13 @@ const helpers = require("./helpers");
const ngCliUtils = require("./ng-cli-utils");

const angularCliAppConfig = ngCliUtils.getAngularCliAppConfig(helpers.root("angular.json"));

// default values for baseHref and deployUrl are taken from
// node_modules/@angular-devkit/build-angular/src/angular-cli-files/models/webpack-configs/styles.js
const ANGULAR_APP_CONFIG = {
config: angularCliAppConfig,
deployUrl: angularCliAppConfig.architect.build.options.deployUrl || "",
baseHref: angularCliAppConfig.architect.build.options.baseHref || "/",
baseHref: angularCliAppConfig.architect.build.options.baseHref || "",
sourceRoot: angularCliAppConfig.sourceRoot,
outputPath: angularCliAppConfig.architect.build.options.outputPath
};
Expand Down Expand Up @@ -39,17 +42,26 @@ function readTsConfig(tsConfigPath) {
}

/**
* The method reads the content of angular.json for getting the path (read with value or replace in "fileReplacements" of environment.
* Read the content of angular.json to get the path of the environment file.
* It returns the path of the replacement file defined in "fileReplacements" of the environment or the default file
* in case the replacement file does not exist.
*
* See: https://github.com/angular/angular-cli/wiki/angular-workspace
*
* @param environment
* @returns {*} - the path of the environment file of the received environment.
* @returns {string} - The path of the environment file of the given environment.
*/
function getEnvironmentFile(environment) {
if (typeof environment === "string") {
let fileName = helpers.root("src/environments/environment.ts");
let fileNameAlt;

// the production config is under "production" section instead of "prod" in angular.json
// see https://github.com/angular/angular-cli/wiki/stories-application-environments
if (environment === "prod") {
environment = "production";
}

let angularCliEnvConfig = ANGULAR_APP_CONFIG.config.architect.build.configurations[environment];

if (angularCliEnvConfig && angularCliEnvConfig.fileReplacements instanceof Array) {
Expand All @@ -59,12 +71,19 @@ function getEnvironmentFile(environment) {
fileNameAlt = helpers.root(angularCliEnvConfig.fileReplacements[0].replace);
}
}
} else {
// for "dev" environment the default environment.ts file is used
if (environment !== "dev") {
throw new Error(
`Configuration for '${environment}' not found in angular.json or it contains invalid fileReplacements section.`
);
}
}

if (fs.existsSync(fileName)) {
return fileName;
} else if (fs.existsSync(fileNameAlt)) {
console.warn(`Could not find environment file for ${environment}, loading default environment file`);
console.warn(`Could not find environment file for '${environment}', loading default environment file`);
return fileNameAlt;
} else {
throw new Error("Environment file not found.");
Expand All @@ -76,7 +95,7 @@ function getEnvironmentFile(environment) {
* Read the tsconfig to determine if we should prefer ES2015 modules.
* Load rxjs path aliases.
* https://github.com/ReactiveX/rxjs/blob/master/doc/pipeable-operators.md#build-and-treeshaking
* @param shouldSupportES2015 Set to true when the output of typescript is >= ES6
* @param shouldSupportES2015 - Set to true when the output of typescript is >= ES6
*/
function rxjsAlias(shouldSupportES2015) {
try {
Expand All @@ -90,9 +109,9 @@ function rxjsAlias(shouldSupportES2015) {
}

/**
* Foreach installed NationalBankBelgium packages, read angular.json file in the root of the module.
* Based on angular.json file, fill an array with the needed assets for the module.
* Then return those to be read by CopyWebpackPlugin.
* Read the assets array in the angular.json file of each NationalBankBelgium package installed in node_modules and concatenate
* them into one single array that will be provided to the CopyWebpackPlugin.
* @returns {Array} An array containing the assets to be copied by CopyWebpackPlugin.
*/
function getNbbAssetsConfig() {
let customAssets = [];
Expand Down
34 changes: 34 additions & 0 deletions showcase/replace-angular-json.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
let fs = require("fs");

const deployUrlPlaceholder = "<stark-dummy-deploy-url>";
const baseHrefPlaceholder = "<stark-dummy-base-href>";

let replacements = [
{ searchValue: `"deployUrl": ""`, replaceValue: `"deployUrl": "${deployUrlPlaceholder}"` },
{ searchValue: `"baseHref": ""`, replaceValue: `"baseHref": "${baseHrefPlaceholder}"` }
];

replaceValuesInFile("angular.json", replacements);

function replaceValuesInFile(fileName, valueReplacements) {
fs.readFile(fileName, "utf8", function(err, data) {
if (err) {
return console.error("Error while reading file => " + err);
}

let result = data;

for (const replacement of valueReplacements) {
const searchValueRegex = new RegExp(replacement.searchValue, "g");
result = result.replace(searchValueRegex, replacement.replaceValue);
}

fs.writeFile(fileName, result, "utf8", function(err) {
if (err) {
return console.error(err);
} else {
return console.log(`${fileName} updated successfully`);
}
});
});
}
81 changes: 81 additions & 0 deletions showcase/replace-urls.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
let fs = require("fs");
let path = require("path");

const filesToChange = [
/index.html/,
/main.*\.css$/,
/runtime~main.*\.js$/,
/runtime~main.*\.js\.map$/,
/runtime~polyfills.*\.js$/,
/runtime~polyfills.*\.js\.map$/
];

if (process.argv.length <= 2) {
console.log("Usage: " + __filename + " deployDir oldDeployDir");
process.exit(-1);
}

let deployDir = "/showcase/" + process.argv[2];

let baseHrefPlaceholder = "<stark-dummy-base-href>";
let deployUrlPlaceholder = "<stark-dummy-deploy-url>";

let urlWithTrailingSlash = deployDir.endsWith("/") ? deployDir : deployDir + "/";
let urlWithoutTrailingSlash = deployDir.endsWith("/") ? deployDir.substring(0, deployDir.length - 1) : deployDir;

let replacements = [
{ searchValue: `"${baseHrefPlaceholder}"`, replaceValue: `"${urlWithTrailingSlash}"` },
{ searchValue: `"${deployUrlPlaceholder}"`, replaceValue: `"${urlWithoutTrailingSlash}"` },
{ searchValue: `"${deployUrlPlaceholder}/`, replaceValue: `"${urlWithTrailingSlash}` },
{ searchValue: `/${baseHrefPlaceholder}/${deployUrlPlaceholder}/`, replaceValue: urlWithTrailingSlash }
];

// if the 3rd param is given (oldDeployDir) then it will be appended to the "showcase" folder and replaced by the new deployDir
if (process.argv[3]) {
deployDir = "showcase/" + process.argv[2]; // no slashes at the beginning nor the end to have one single replacement
let oldDeployDir = "showcase/" + process.argv[3]; // no slashes at the beginning nor the end to have one single replacement

replacements = [{ searchValue: oldDeployDir, replaceValue: deployDir }];
}

let outputDir = "." + path.sep + "dist";

fs.readdir(outputDir, function(err, items) {
if (err) {
return console.error("Error while reading directory => " + err);
}

for (const item of items) {
for (const fileRegex of filesToChange) {
if (item.match(fileRegex)) {
let fullFilePath = outputDir + path.sep + item;
replaceValuesInFile(fullFilePath, replacements);

break;
}
}
}
});

function replaceValuesInFile(fileName, valueReplacements) {
fs.readFile(fileName, "utf8", function(err, data) {
if (err) {
return console.error("Error while reading file => " + err);
}

let result = data;

for (const replacement of valueReplacements) {
const searchValueRegex = new RegExp(replacement.searchValue, "g");
result = result.replace(searchValueRegex, replacement.replaceValue);
}

fs.writeFile(fileName, result, "utf8", function(err) {
if (err) {
return console.error(err);
} else {
return console.log(`${fileName} updated successfully`);
}
});
});
}

0 comments on commit 8dc6e8e

Please sign in to comment.