Skip to content
This repository was archived by the owner on Aug 7, 2021. It is now read-only.

feat: NativeScript bootstrap transformer #634

Merged
merged 4 commits into from
Aug 17, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,10 @@ plugins/NativeScriptAngularCompilerPlugin.d.ts
plugins/NativeScriptAngularCompilerPlugin.js
plugins/NativeScriptAngularCompilerPlugin.js.map

transformers/ns-replace-bootstrap.d.ts
transformers/ns-replace-bootstrap.js
transformers/ns-replace-bootstrap.js.map

plugins/PlatformFSPlugin.d.ts
plugins/PlatformFSPlugin.js
plugins/PlatformFSPlugin.js.map
Expand Down
2 changes: 1 addition & 1 deletion dependencyManager.js
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ function getRequiredDeps(packageJson) {
};

if (!dependsOn(packageJson, "@angular-devkit/build-angular")) {
deps["@ngtools/webpack"] = "~6.1.0";
deps["@ngtools/webpack"] = "~6.2.0-beta.3";
}

return deps;
Expand Down
4 changes: 2 additions & 2 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@ const {
isIos,
} = require("./projectHelpers");

Object.assign(exports, require('./plugins'));
Object.assign(exports, require('./host/resolver'));
Object.assign(exports, require("./plugins"));
Object.assign(exports, require("./host/resolver"));

exports.getAotEntryModule = function (appDirectory) {
verifyEntryModuleDirectory(appDirectory);
Expand Down
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,7 @@
"devDependencies": {
"@types/node": "^8.0.0",
"conventional-changelog-cli": "^1.3.22",
"typescript": "~2.7.2"
"typescript": "~2.9.1",
"@ngtools/webpack": "~6.2.0-beta.3"
}
}
29 changes: 15 additions & 14 deletions templates/webpack.angular.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ const { join, relative, resolve, sep } = require("path");
const webpack = require("webpack");
const nsWebpack = require("nativescript-dev-webpack");
const nativescriptTarget = require("nativescript-dev-webpack/nativescript-target");
const { nsReplaceBootstrap } = require("nativescript-dev-webpack/transformers/ns-replace-bootstrap");
const CleanWebpackPlugin = require("clean-webpack-plugin");
const CopyWebpackPlugin = require("copy-webpack-plugin");
const { BundleAnalyzerPlugin } = require("webpack-bundle-analyzer");
Expand Down Expand Up @@ -46,11 +47,18 @@ module.exports = env => {
const appFullPath = resolve(projectRoot, appPath);
const appResourcesFullPath = resolve(projectRoot, appResourcesPath);

const entryModule = aot ?
nsWebpack.getAotEntryModule(appFullPath) :
`${nsWebpack.getEntryModule(appFullPath)}.ts`;
const entryModule = `${nsWebpack.getEntryModule(appFullPath)}.ts`;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please remove the getAotEntryModule function from index.js as well.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's a breaking change if we remove it completely.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yep. We discussed to introduce a Deprecated decorator in another PR.

const entryPath = `.${sep}${entryModule}`;

const ngCompilerPlugin = new AngularCompilerPlugin({
hostReplacementPaths: nsWebpack.getResolver([platform, "tns"]),
platformTransformers: aot ? [nsReplaceBootstrap(() => ngCompilerPlugin)] : null,
mainPath: resolve(appPath, entryModule),
tsConfigPath: join(__dirname, "tsconfig.esm.json"),
skipCodeGeneration: !aot,
sourceMap: !!sourceMap,
});

const config = {
mode: uglify ? "production" : "development",
context: appFullPath,
Expand Down Expand Up @@ -107,7 +115,7 @@ module.exports = env => {
test: (module, chunks) => {
const moduleName = module.nameForCondition ? module.nameForCondition() : '';
return /[\\/]node_modules[\\/]/.test(moduleName) ||
appComponents.some(comp => comp === moduleName);
appComponents.some(comp => comp === moduleName);
},
enforce: true,
},
Expand Down Expand Up @@ -195,10 +203,9 @@ module.exports = env => {
// Define useful constants like TNS_WEBPACK
new webpack.DefinePlugin({
"global.TNS_WEBPACK": "true",
"process": undefined,
}),
// Remove all files from the out dir.
new CleanWebpackPlugin([ `${dist}/**/*` ]),
new CleanWebpackPlugin([`${dist}/**/*`]),
// Copy native app resources to out dir.
new CopyWebpackPlugin([
{
Expand All @@ -221,19 +228,13 @@ module.exports = env => {
// For instructions on how to set up workers with webpack
// check out https://github.com/nativescript/worker-loader
new NativeScriptWorkerPlugin(),

new AngularCompilerPlugin({
hostReplacementPaths: nsWebpack.getResolver([platform, "tns"]),
mainPath: resolve(appPath, "main.ts"),
tsConfigPath: join(__dirname, "tsconfig.esm.json"),
skipCodeGeneration: !aot,
sourceMap: !!sourceMap,
}),
ngCompilerPlugin,
// Does IPC communication with the {N} CLI to notify events when running in watch mode.
new nsWebpack.WatchStateLoggerPlugin(),
],
};


if (report) {
// Generate report files for bundles content
config.plugins.push(new BundleAnalyzerPlugin({
Expand Down
3 changes: 3 additions & 0 deletions transformers/ns-replace-bootstrap.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import * as ts from 'typescript';
import { AngularCompilerPlugin } from '@ngtools/webpack';
export declare function nsReplaceBootstrap(getNgCompiler: () => AngularCompilerPlugin): ts.TransformerFactory<ts.SourceFile>;
66 changes: 66 additions & 0 deletions transformers/ns-replace-bootstrap.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions transformers/ns-replace-bootstrap.js.map

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

103 changes: 103 additions & 0 deletions transformers/ns-replace-bootstrap.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
import { dirname, relative } from 'path';
import * as ts from 'typescript';
import {
StandardTransform,
TransformOperation,
collectDeepNodes,
insertStarImport,
ReplaceNodeOperation,
makeTransform
} from "@ngtools/webpack/src/transformers";
import { workaroundResolve } from '@ngtools/webpack/src/compiler_host';
import { AngularCompilerPlugin } from '@ngtools/webpack';

export function nsReplaceBootstrap(getNgCompiler: () => AngularCompilerPlugin): ts.TransformerFactory<ts.SourceFile> {
const shouldTransform = (fileName) => !fileName.endsWith('.ngfactory.ts') && !fileName.endsWith('.ngstyle.ts');
const getTypeChecker = () => getNgCompiler().typeChecker;

const standardTransform: StandardTransform = function (sourceFile: ts.SourceFile) {
const ops: TransformOperation[] = [];
const ngCompiler = getNgCompiler();

const entryModule = ngCompiler.entryModule
? { path: workaroundResolve(ngCompiler.entryModule.path), className: getNgCompiler().entryModule.className }
: ngCompiler.entryModule;

if (!shouldTransform(sourceFile.fileName) || !entryModule) {
return ops;
}

// Find all identifiers.
const entryModuleIdentifiers = collectDeepNodes<ts.Identifier>(sourceFile,
ts.SyntaxKind.Identifier)
.filter(identifier => identifier.text === entryModule.className);

if (entryModuleIdentifiers.length === 0) {
return [];
}

const relativeEntryModulePath = relative(dirname(sourceFile.fileName), entryModule.path);
const normalizedEntryModulePath = `./${relativeEntryModulePath}`.replace(/\\/g, '/');

// Find the bootstrap calls.
entryModuleIdentifiers.forEach(entryModuleIdentifier => {
// Figure out if it's a `platformNativeScriptDynamic().bootstrapModule(AppModule)` call.
if (!(
entryModuleIdentifier.parent
&& entryModuleIdentifier.parent.kind === ts.SyntaxKind.CallExpression
)) {
return;
}

const callExpr = entryModuleIdentifier.parent as ts.CallExpression;

if (callExpr.expression.kind !== ts.SyntaxKind.PropertyAccessExpression) {
return;
}

const propAccessExpr = callExpr.expression as ts.PropertyAccessExpression;

if (propAccessExpr.name.text !== 'bootstrapModule'
|| propAccessExpr.expression.kind !== ts.SyntaxKind.CallExpression) {
return;
}

const bootstrapModuleIdentifier = propAccessExpr.name;
const innerCallExpr = propAccessExpr.expression as ts.CallExpression;

if (!(
innerCallExpr.expression.kind === ts.SyntaxKind.Identifier
&& (innerCallExpr.expression as ts.Identifier).text === 'platformNativeScriptDynamic'
)) {
return;
}

const platformBrowserDynamicIdentifier = innerCallExpr.expression as ts.Identifier;

const idPlatformBrowser = ts.createUniqueName('__NgCli_bootstrap_');
const idNgFactory = ts.createUniqueName('__NgCli_bootstrap_');

// Add the transform operations.
const factoryClassName = entryModule.className + 'NgFactory';
const factoryModulePath = normalizedEntryModulePath + '.ngfactory';
ops.push(
// Replace the entry module import.
...insertStarImport(sourceFile, idNgFactory, factoryModulePath),
new ReplaceNodeOperation(sourceFile, entryModuleIdentifier,
ts.createPropertyAccess(idNgFactory, ts.createIdentifier(factoryClassName))),

// Replace the platformBrowserDynamic import.
...insertStarImport(sourceFile, idPlatformBrowser, 'nativescript-angular/platform-static'),
new ReplaceNodeOperation(sourceFile, platformBrowserDynamicIdentifier,
ts.createPropertyAccess(idPlatformBrowser, 'platformNativeScript')),

new ReplaceNodeOperation(sourceFile, bootstrapModuleIdentifier,
ts.createIdentifier('bootstrapModuleFactory')),
);
});

return ops;
};

return makeTransform(standardTransform, getTypeChecker);
}
1 change: 1 addition & 0 deletions tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
"files": [
"plugins/PlatformFSPlugin.ts",
"plugins/WatchStateLoggerPlugin.ts",
"transformers/ns-replace-bootstrap.ts",
"host/resolver.ts"
]
}