angular-cli icon indicating copy to clipboard operation
angular-cli copied to clipboard

how do you dynamically update index.html via the angular CLI build?

Open jordan112 opened this issue 9 years ago • 7 comments

Bug Report or Feature Request (mark with an x)

- [ ] bug report -> please search issues before submitting
- [X] feature request

Versions

cli 1.4.3 node: v7.6.0 npm: 4.1.2

Desired functionality

The CLI generates a index.html file. There are various places in that file that I need to dynamically update. Is there a way to do this using the Angular CLI build process?

###Use cases

  • Internationalization: i18n has not access into the index.html, only the components beneath it. How do you dynamically bring in messages, such as "loading..." in other languages?

  • The tag requires lang="en", etc. I could hard code en, but I have 12 different languages and I need to have the proper locale-id loaded in that attribute. We use AOT and generate 12 different static sites using all built in CLI

  • HTML page title: This requires different languages as well, but don't know how to get them there. There is the Title service, but that wasn't working for me. https://angular.io/api/platform-browser/Title

jordan112 avatar Sep 25 '17 16:09 jordan112

I've solved issues like this by building out some scripts that run before and after my ng build process.

Using npm scripts and local node.js apps you can ensure files are generated before the build and files are modified after the build. If you want to modify your index.html after the build completes you can use something like https://github.com/cheeriojs/cheerio to read in your html and interact with the text as DOM.

Your package.json would have a script like this "build": "node build/run-script-before-build.js && ng build --prod && node build/run-script-after-build.js"

seangwright avatar Sep 25 '17 17:09 seangwright

We don't have functionality to change index.html dynamically, no. It has been discussed a few times but it's also fairly easy to do on your own like @sgwatgit suggested.

filipesilva avatar Sep 27 '17 10:09 filipesilva

Thank you for your responses and your solution @sgwatgit

I'm posting an example of the after script file that worked well for me. The json file is just a name value pair of where I keep my translations to swap in. Hopefully this will help someone else.

const cheerio = require('cheerio')
const fs = require('fs');
const _ = require('lodash');
const buildTranslations = require('./build.translations.json');
const indexFilePath = 'dist/index.html'
const localeId = 'zh-tw'

console.log('After build script started...')

// read our index file
console.log('About to rewrite file: ', indexFilePath);
fs.readFile(indexFilePath, 'utf8', function (err,data) {
    if (err) {
      return console.log(err);
    }

    // load html into cheerio so we can manipulate DOM
    const $ = cheerio.load(data)

    const pageTitle = _.find(buildTranslations.pageTitles, { 'localeID': localeId });

    console.log('pageTitle to update: ', pageTitle)

    if(pageTitle){
        // update title by language
        $('title').text(pageTitle.content)
    }
    
    // update html tag for proper lang
    $('html').attr('lang', localeId)
    $('html').attr('xml:lang', localeId)

    // now write that file back
    fs.writeFile(indexFilePath, $.html(), function (err) {
        if (err) return console.log(err);
        console.log('Successfully rewrote index html');
    });
  });

jordan112 avatar Sep 27 '17 11:09 jordan112

Hey,

@sgwatgit @jordan112 How to run a post script regarding ng serve command?

Thanks, Ricky

RickyJiao avatar Jun 09 '18 08:06 RickyJiao

@RickyJiao

What you are asking for is tricky. The ng serve process continues running, watching for file changes and rebuilding the project until something (typically the user via ctrl+C) terminates the script. When running ng serve via npm start, the poststart script will never run due to the premature termination, making it pretty useless.

If you need something to run at the same time as ng serve you can use something like concurrently

"scripts": {
  "start": "concurrently \"ng serve\" \"do-also script\"",
  "poststart": "node do-something.js" // <-- will never run
}

But if you are trying to alter the served build on the fly, you'd be better served working within the constraints of the angular.json file, or ejecting the webpack configuration and implementing a custom serve process.

clcarter avatar Jun 25 '18 19:06 clcarter

Build-scripts and such semi-static hacks obviously don't solve the real problem. What if I want to pull that data from some database, at the time of page load? And with all the talk of dynamic localization, the html5 lang attribute needs to be accessible somehow. I think this issue should be re-opened.

kaleidocore avatar Aug 25 '18 03:08 kaleidocore

This issue has been automatically locked due to inactivity. Please file a new issue if you are encountering a similar or related problem.

Read more about our automatic conversation locking policy.

This action has been performed automatically by a bot.