mirror of
https://github.com/angular/angular
synced 2026-05-24 09:28:37 +00:00
As outlined in the previous commit which enabled the `esModuleInterop` TypeScript compiler option, we need to update all namespace imports for `typescript` to default imports. This is needed to allow for TypeScript to be imported at runtime from an ES module. Similar changes are needed for modules like `semver` where the types incorrectly suggest named exports that will not exist at runtime when imported from ESM. This commit refactors all imports to match with the lint rule we have configured in the previous commit. See the previous commit for more details on why certain imports have been changed. A special case are the imports to `@babel/core` and `@babel/types`. For these a special interop is needed as both default imports, or named imports break the other module format. e.g default imports would work well for ESM, but it breaks for CJS. For CJS, the named imports would only work, but in ESM, only the default export exist. We work around this for now until the devmode is using ESM as well (which would be consistent with prodmode and gives us more valuable test results). More details on the interop can be found in the `babel_core.ts` files (two interops are needed for both localize/or the compiler-cli). PR Close #43431
194 lines
7.4 KiB
TypeScript
194 lines
7.4 KiB
TypeScript
/**
|
|
* @license
|
|
* Copyright Google LLC 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 ts from 'typescript';
|
|
|
|
import {isClassMetadata, MetadataCollector} from '../../src/metadata/index';
|
|
import {getInlineResourcesTransformFactory, InlineResourcesMetadataTransformer} from '../../src/transformers/inline_resources';
|
|
import {MetadataCache} from '../../src/transformers/metadata_cache';
|
|
import {MockAotContext, MockCompilerHost} from '../mocks';
|
|
|
|
describe('inline resources transformer', () => {
|
|
describe('decorator input', () => {
|
|
describe('should not touch unrecognized decorators', () => {
|
|
it('Not from @angular/core', () => {
|
|
expect(convert(`declare const Component: Function;
|
|
@Component({templateUrl: './thing.html'}) class Foo {}`))
|
|
.toContain('templateUrl');
|
|
});
|
|
it('missing @ sign', () => {
|
|
expect(convert(`import {Component} from '@angular/core';
|
|
Component({templateUrl: './thing.html'}) class Foo {}`))
|
|
.toContain('templateUrl');
|
|
});
|
|
it('too many arguments to @Component', () => {
|
|
expect(convert(`import {Component} from '@angular/core';
|
|
@Component(1, {templateUrl: './thing.html'}) class Foo {}`))
|
|
.toContain('templateUrl');
|
|
});
|
|
it('wrong argument type to @Component', () => {
|
|
expect(convert(`import {Component} from '@angular/core';
|
|
@Component([{templateUrl: './thing.html'}]) class Foo {}`))
|
|
.toContain('templateUrl');
|
|
});
|
|
});
|
|
|
|
it('should replace templateUrl', () => {
|
|
const actual = convert(`import {Component} from '@angular/core';
|
|
@Component({
|
|
templateUrl: './thing.html',
|
|
otherProp: 3,
|
|
}) export class Foo {}`);
|
|
expect(actual).not.toContain('templateUrl:');
|
|
expect(actual.replace(/\s+/g, ' '))
|
|
.toContain(
|
|
'Foo = __decorate([ (0, core_1.Component)({ template: "Some template", otherProp: 3 }) ], Foo)');
|
|
});
|
|
it('should allow different quotes', () => {
|
|
const actual = convert(`import {Component} from '@angular/core';
|
|
@Component({"templateUrl": \`./thing.html\`}) export class Foo {}`);
|
|
expect(actual).not.toContain('templateUrl:');
|
|
expect(actual).toContain('{ template: "Some template" }');
|
|
});
|
|
it('should replace styleUrls', () => {
|
|
const actual = convert(`import {Component} from '@angular/core';
|
|
@Component({
|
|
styleUrls: ['./thing1.css', './thing2.css'],
|
|
})
|
|
export class Foo {}`);
|
|
expect(actual).not.toContain('styleUrls:');
|
|
expect(actual).toContain('styles: [".some_style {}", ".some_other_style {}"]');
|
|
});
|
|
it('should preserve existing styles', () => {
|
|
const actual = convert(`import {Component} from '@angular/core';
|
|
@Component({
|
|
styles: ['h1 { color: blue }'],
|
|
styleUrls: ['./thing1.css'],
|
|
})
|
|
export class Foo {}`);
|
|
expect(actual).not.toContain('styleUrls:');
|
|
expect(actual).toContain(`styles: ['h1 { color: blue }', ".some_style {}"]`);
|
|
});
|
|
it('should handle empty styleUrls', () => {
|
|
const actual = convert(`import {Component} from '@angular/core';
|
|
@Component({styleUrls: [], styles: []}) export class Foo {}`);
|
|
expect(actual).not.toContain('styleUrls:');
|
|
expect(actual).not.toContain('styles:');
|
|
});
|
|
});
|
|
describe('annotation input', () => {
|
|
it('should replace templateUrl', () => {
|
|
const actual = convert(`import {Component} from '@angular/core';
|
|
declare const NotComponent: Function;
|
|
|
|
export class Foo {
|
|
static decorators: {type: Function, args?: any[]}[] = [
|
|
{
|
|
type: NotComponent,
|
|
args: [],
|
|
},{
|
|
type: Component,
|
|
args: [{
|
|
templateUrl: './thing.html'
|
|
}],
|
|
}];
|
|
}
|
|
`);
|
|
expect(actual).not.toContain('templateUrl:');
|
|
expect(actual.replace(/\s+/g, ' '))
|
|
.toMatch(
|
|
/Foo\.decorators = [{ .*type: core_1\.Component, args: [{ template: "Some template" }]/);
|
|
});
|
|
it('should replace styleUrls', () => {
|
|
const actual = convert(`import {Component} from '@angular/core';
|
|
declare const NotComponent: Function;
|
|
|
|
export class Foo {
|
|
static decorators: {type: Function, args?: any[]}[] = [{
|
|
type: Component,
|
|
args: [{
|
|
styleUrls: ['./thing1.css', './thing2.css'],
|
|
}],
|
|
}];
|
|
}
|
|
`);
|
|
expect(actual).not.toContain('styleUrls:');
|
|
expect(actual.replace(/\s+/g, ' '))
|
|
.toMatch(
|
|
/Foo\.decorators = [{ .*type: core_1\.Component, args: [{ style: "Some template" }]/);
|
|
});
|
|
});
|
|
});
|
|
|
|
describe('metadata transformer', () => {
|
|
it('should transform decorators', () => {
|
|
const source = `import {Component} from '@angular/core';
|
|
@Component({
|
|
templateUrl: './thing.html',
|
|
styleUrls: ['./thing1.css', './thing2.css'],
|
|
styles: ['h1 { color: red }'],
|
|
})
|
|
export class Foo {}
|
|
`;
|
|
const sourceFile = ts.createSourceFile(
|
|
'someFile.ts', source, ts.ScriptTarget.Latest, /* setParentNodes */ true);
|
|
const cache = new MetadataCache(
|
|
new MetadataCollector(), /* strict */ true,
|
|
[new InlineResourcesMetadataTransformer(
|
|
{loadResource, resourceNameToFileName: (u: string) => u})]);
|
|
const metadata = cache.getMetadata(sourceFile);
|
|
expect(metadata).toBeDefined('Expected metadata from test source file');
|
|
if (metadata) {
|
|
const classData = metadata.metadata['Foo'];
|
|
expect(classData && isClassMetadata(classData))
|
|
.toBeDefined(`Expected metadata to contain data for Foo`);
|
|
if (classData && isClassMetadata(classData)) {
|
|
expect(JSON.stringify(classData)).not.toContain('templateUrl');
|
|
expect(JSON.stringify(classData)).toContain('"template":"Some template"');
|
|
expect(JSON.stringify(classData)).not.toContain('styleUrls');
|
|
expect(JSON.stringify(classData))
|
|
.toContain('"styles":["h1 { color: red }",".some_style {}",".some_other_style {}"]');
|
|
}
|
|
}
|
|
});
|
|
});
|
|
|
|
function loadResource(path: string): Promise<string>|string {
|
|
if (path === './thing.html') return 'Some template';
|
|
if (path === './thing1.css') return '.some_style {}';
|
|
if (path === './thing2.css') return '.some_other_style {}';
|
|
throw new Error('No fake data for path ' + path);
|
|
}
|
|
|
|
function convert(source: string) {
|
|
const baseFileName = 'someFile';
|
|
const moduleName = '/' + baseFileName;
|
|
const fileName = moduleName + '.ts';
|
|
const context = new MockAotContext('/', {[baseFileName + '.ts']: source});
|
|
const host = new MockCompilerHost(context);
|
|
|
|
const program = ts.createProgram(
|
|
[fileName], {
|
|
module: ts.ModuleKind.CommonJS,
|
|
target: ts.ScriptTarget.ES2017,
|
|
},
|
|
host);
|
|
const moduleSourceFile = program.getSourceFile(fileName);
|
|
const transformers: ts.CustomTransformers = {
|
|
before: [getInlineResourcesTransformFactory(
|
|
program, {loadResource, resourceNameToFileName: (u: string) => u})]
|
|
};
|
|
let result = '';
|
|
program.emit(
|
|
moduleSourceFile, (emittedFileName, data, writeByteOrderMark, onError, sourceFiles) => {
|
|
if (fileName.startsWith(moduleName)) {
|
|
result = data;
|
|
}
|
|
}, undefined, undefined, transformers);
|
|
return result;
|
|
}
|