feat(ivy): support i18n without closure (#28689)

So far using runtime i18n with ivy meant that you needed to use Closure and `goog.getMsg` (or a polyfill). This PR changes the compiler to output both closure & non-closure code, while the unused option will be tree-shaken by minifiers.
This means that if you use the Angular CLI with ivy and load a translations file, you can use i18n and the application will not throw at runtime.
For now it will not translate your application, but at least you can try ivy without having to remove all of your i18n code and configuration.
PR Close #28689
This commit is contained in:
Olivier Combe
2019-04-11 11:17:49 +02:00
committed by Igor Minar
parent 387fbb8106
commit 91c7b451d5
22 changed files with 1397 additions and 564 deletions

View File

@ -134,6 +134,8 @@ export {
Δi18nEnd,
Δi18nApply,
Δi18nPostprocess,
i18nConfigureLocalize as ɵi18nConfigureLocalize,
Δi18nLocalize,
setClassMetadata as ɵsetClassMetadata,
ΔresolveWindow,
ΔresolveDocument,

View File

@ -6,6 +6,8 @@
* found in the LICENSE file at https://angular.io/license
*/
import '../util/ng_i18n_closure_mode';
import {SRCSET_ATTRS, URI_ATTRS, VALID_ATTRS, VALID_ELEMENTS, getTemplateContent} from '../sanitization/html_sanitizer';
import {InertBodyHelper} from '../sanitization/inert_body';
import {_sanitizeUrl, sanitizeSrcset} from '../sanitization/url_sanitizer';
@ -1604,3 +1606,38 @@ function parseNodes(
}
}
}
let TRANSLATIONS: {[key: string]: string} = {};
export interface I18nLocalizeOptions { translations: {[key: string]: string}; }
/**
* Set the configuration for `i18nLocalize`.
*
* @deprecated this method is temporary & should not be used as it will be removed soon
*/
export function i18nConfigureLocalize(options: I18nLocalizeOptions = {
translations: {}
}) {
TRANSLATIONS = options.translations;
}
const LOCALIZE_PH_REGEXP = /\{\$(.*?)\}/g;
/**
* A goog.getMsg-like function for users that do not use Closure.
*
* This method is required as a *temporary* measure to prevent i18n tests from being blocked while
* running outside of Closure Compiler. This method will not be needed once runtime translation
* service support is introduced.
*
* @publicApi
* @deprecated this method is temporary & should not be used as it will be removed soon
*/
export function Δi18nLocalize(input: string, placeholders: {[key: string]: string} = {}) {
if (typeof TRANSLATIONS[input] !== 'undefined') { // to account for empty string
input = TRANSLATIONS[input];
}
return Object.keys(placeholders).length ?
input.replace(LOCALIZE_PH_REGEXP, (match, key) => placeholders[key] || '') :
input;
}

View File

@ -107,6 +107,8 @@ export {
Δi18nEnd,
Δi18nApply,
Δi18nPostprocess,
i18nConfigureLocalize,
Δi18nLocalize,
} from './i18n';
export {NgModuleFactory, NgModuleRef, NgModuleType} from './ng_module_ref';

View File

@ -117,6 +117,7 @@ export const angularCoreEnv: {[name: string]: Function} = {
'Δi18nEnd': r3.Δi18nEnd,
'Δi18nApply': r3.Δi18nApply,
'Δi18nPostprocess': r3.Δi18nPostprocess,
'Δi18nLocalize': r3.Δi18nLocalize,
'ΔresolveWindow': r3.ΔresolveWindow,
'ΔresolveDocument': r3.ΔresolveDocument,
'ΔresolveBody': r3.ΔresolveBody,

View File

@ -6,6 +6,8 @@
* found in the LICENSE file at https://angular.io/license
*/
import {global} from './global';
declare global {
const ngDevMode: null|NgDevModePerfCounters;
interface NgDevModePerfCounters {
@ -38,8 +40,6 @@ declare global {
}
}
declare let global: any;
export function ngDevModeResetPerfCounters(): NgDevModePerfCounters {
const newCounters: NgDevModePerfCounters = {
firstTemplatePass: 0,
@ -69,31 +69,20 @@ export function ngDevModeResetPerfCounters(): NgDevModePerfCounters {
stylingApply: 0,
stylingApplyCacheMiss: 0,
};
// NOTE: Under Ivy we may have both window & global defined in the Node
// environment since ensureDocument() in render3.ts sets global.window.
if (typeof window != 'undefined') {
// Make sure to refer to ngDevMode as ['ngDevMode'] for closure.
(window as any)['ngDevMode'] = newCounters;
}
if (typeof global != 'undefined') {
// Make sure to refer to ngDevMode as ['ngDevMode'] for closure.
(global as any)['ngDevMode'] = newCounters;
}
if (typeof self != 'undefined') {
// Make sure to refer to ngDevMode as ['ngDevMode'] for closure.
(self as any)['ngDevMode'] = newCounters;
}
// Make sure to refer to ngDevMode as ['ngDevMode'] for closure.
global['ngDevMode'] = newCounters;
return newCounters;
}
/**
* This checks to see if the `ngDevMode` has been set. If yes,
* than we honor it, otherwise we default to dev mode with additional checks.
* then we honor it, otherwise we default to dev mode with additional checks.
*
* The idea is that unless we are doing production build where we explicitly
* set `ngDevMode == false` we should be helping the developer by providing
* as much early warning and errors as possible.
*/
if (typeof ngDevMode === 'undefined' || ngDevMode) {
if (typeof global['ngDevMode'] === 'undefined' || global['ngDevMode']) {
ngDevModeResetPerfCounters();
}

View File

@ -0,0 +1,19 @@
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {global} from './global';
declare global {
const ngI18nClosureMode: boolean;
}
if (typeof global['ngI18nClosureMode'] === 'undefined') {
// Make sure to refer to ngI18nClosureMode as ['ngI18nClosureMode'] for closure.
global['ngI18nClosureMode'] =
typeof global['goog'] !== 'undefined' && typeof global['goog'].getMsg === 'function';
}

View File

@ -6,10 +6,10 @@
* found in the LICENSE file at https://angular.io/license
*/
import {Component, Directive, NO_ERRORS_SCHEMA, QueryList, TemplateRef, ViewChild, ViewChildren, ViewContainerRef} from '@angular/core';
import {Component, Directive, NO_ERRORS_SCHEMA, QueryList, TemplateRef, ViewChild, ViewChildren, ViewContainerRef, ɵi18nConfigureLocalize} from '@angular/core';
import {TestBed} from '@angular/core/testing';
import {expect} from '@angular/platform-browser/testing/src/matchers';
import {ivyEnabled, onlyInIvy, polyfillGoogGetMsg} from '@angular/private/testing';
import {ivyEnabled, onlyInIvy} from '@angular/private/testing';
describe('ViewContainerRef', () => {
@ -22,7 +22,7 @@ describe('ViewContainerRef', () => {
};
beforeEach(() => {
polyfillGoogGetMsg(TRANSLATIONS);
ɵi18nConfigureLocalize({translations: TRANSLATIONS});
TestBed.configureTestingModule(
{declarations: [StructDir, ViewContainerRefComp, ViewContainerRefApp, DestroyCasesComp]});
});

View File

@ -23,14 +23,6 @@
property renaming.
-->
<script>
// `goog.getMsg()` will be provided by Closure
const translations = {
'Hello World!': 'Bonjour Monde!',
'Hello Title!': 'Bonjour Titre!',
};
window.goog = window.goog || {};
window.goog.getMsg = (key) => translations[key] || key;
document.write('<script src="' +
(document.location.search.endsWith('debug') ? '/bundle.min_debug.js' : '/bundle.min.js') +
'"></' + 'script>');

View File

@ -6,7 +6,14 @@
* found in the LICENSE file at https://angular.io/license
*/
import {Component, NgModule, ɵrenderComponent as renderComponent} from '@angular/core';
import {Component, NgModule, ɵi18nConfigureLocalize, ɵrenderComponent as renderComponent} from '@angular/core';
const translations = {
'Hello World!': 'Bonjour Monde!',
'Hello Title!': 'Bonjour Titre!',
};
ɵi18nConfigureLocalize({translations});
@Component({
selector: 'hello-world',

View File

@ -116,6 +116,9 @@
{
"name": "_currentInjector"
},
{
"name": "_global"
},
{
"name": "catchInjectorError"
},
@ -140,6 +143,9 @@
{
"name": "getClosureSafeProperty"
},
{
"name": "getGlobal"
},
{
"name": "getInjectableDef"
},

View File

@ -7,10 +7,16 @@
*/
import '@angular/core/test/bundling/util/src/reflect_metadata';
/**
* TODO(ocombe): replace this with the real runtime i18n service configuration
* For now we define inline translations that are added with the function `ɵi18nConfigureLocalize`,
* but this function will go away once we have finished designing and implementing the new runtime
* service. At this point we should revisit this code and update it to use that new service.
* See FW-114.
*/
import './translations';
import {CommonModule} from '@angular/common';
import {Component, Injectable, NgModule, ViewEncapsulation, ɵmarkDirty as markDirty, ɵrenderComponent as renderComponent} from '@angular/core';
// TODO(ocombe): replace this with the real runtime i18n service
import {localize} from './translations';
import {Component, Injectable, NgModule, ViewEncapsulation, ɵmarkDirty as markDirty, ɵrenderComponent as renderComponent, Δi18nLocalize as localize} from '@angular/core';
class Todo {
editing: boolean;

View File

@ -6,8 +6,7 @@
* found in the LICENSE file at https://angular.io/license
*/
declare var global: any;
declare var window: any;
import {ɵi18nConfigureLocalize} from '@angular/core';
export const translations: {[key: string]: string} = {
'What needs to be done?': `Qu'y a-t-il à faire ?`,
@ -25,18 +24,4 @@ export const translations: {[key: string]: string} = {
'Demonstrate internationalization': `Démontrer l'internationalisation`
};
// Runtime i18n uses Closure goog.getMsg for now
// It will be replaced by the runtime service for external people
const glob = typeof global !== 'undefined' ? global : window;
glob.goog = glob.goog || {};
glob.goog.getMsg =
glob.goog.getMsg || function(input: string, placeholders: {[key: string]: string} = {}) {
if (typeof translations[input] !== 'undefined') { // to account for empty string
input = translations[input];
}
return Object.keys(placeholders).length ?
input.replace(/\{\$(.*?)\}/g, (match, key) => placeholders[key] || '') :
input;
};
export const localize = goog.getMsg;
ɵi18nConfigureLocalize({translations});

View File

@ -6,10 +6,10 @@
* found in the LICENSE file at https://angular.io/license
*/
import {Component, ContentChild, ContentChildren, Directive, QueryList, TemplateRef, ViewChild, ViewContainerRef} from '@angular/core';
import {Component, ContentChild, ContentChildren, Directive, QueryList, TemplateRef, ViewChild, ViewContainerRef, ɵi18nConfigureLocalize} from '@angular/core';
import {TestBed} from '@angular/core/testing';
import {expect} from '@angular/platform-browser/testing/src/matchers';
import {onlyInIvy, polyfillGoogGetMsg} from '@angular/private/testing';
import {onlyInIvy} from '@angular/private/testing';
@Directive({
selector: '[tplRef]',
@ -79,7 +79,7 @@ const getFixtureWithOverrides = (overrides = {}) => {
onlyInIvy('Ivy i18n logic').describe('i18n', function() {
beforeEach(() => {
polyfillGoogGetMsg(TRANSLATIONS);
ɵi18nConfigureLocalize({translations: TRANSLATIONS});
TestBed.configureTestingModule({declarations: [MyComp, DirectiveWithTplRef]});
});

View File

@ -11,7 +11,7 @@ import {AfterContentInit, AfterViewInit, Component, ContentChildren, Directive,
import {TestBed} from '@angular/core/testing';
import {getDOM} from '@angular/platform-browser/src/dom/dom_adapter';
import {expect} from '@angular/platform-browser/testing/src/matchers';
import {modifiedInIvy, polyfillGoogGetMsg} from '@angular/private/testing';
import {modifiedInIvy} from '@angular/private/testing';
if (ivyEnabled) {
describe('ivy', () => { declareTests(); });
@ -24,11 +24,6 @@ function declareTests(config?: {useJit: boolean}) {
describe('<ng-container>', function() {
beforeEach(() => {
// Injecting goog.getMsg-like function into global scope to unblock tests run outside of
// Closure Compiler. It's a *temporary* measure until runtime translation service support is
// introduced.
polyfillGoogGetMsg();
TestBed.configureCompiler({...config});
TestBed.configureTestingModule({
declarations: [