diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 731d8601..f65a4183 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -18,7 +18,7 @@ First of all, thank you for taking the time to contribute! -Before starting, make yourself familiar with the `nativescript-dev-webpack`'s [documentation](http://docs.nativescript.org/best-practices/bundling-with-webpack) and the official [NativeScript Code Of Conduct]( https://github.com/NativeScript/codeofconduct). +Before starting, make yourself familiar with the `@nativescript/webpack`'s [documentation](http://docs.nativescript.org/best-practices/bundling-with-webpack) and the official [NativeScript Code Of Conduct]( https://github.com/NativeScript/codeofconduct). ## Project Structure @@ -67,7 +67,7 @@ NOTE: There are three test apps in the repository, located in the `/demo` direct cd demo/AngularApp ``` -2. Install your local copy of the `nativescript-dev-webpack` plugin. +2. Install your local copy of the `@nativescript/webpack` plugin. ```bash npm run setup ``` diff --git a/PULL_REQUEST_TESTS.md b/PULL_REQUEST_TESTS.md index 1da1dec0..395e4fc4 100644 --- a/PULL_REQUEST_TESTS.md +++ b/PULL_REQUEST_TESTS.md @@ -3,9 +3,9 @@ This document describes comment messages available to execute tests on pull requ |Comment |Commit Status Context|Description| |:----------------------:|:-------------------:|:---------:| |`run ci` | |Run all below.| -|`js`|ci/jenkins/webpack-js|Pack the *nativescript-dev-webpack* plugin and bundle the [template-hello-world](https://github.com/NativeScript/template-hello-world) template app. | -|`ts`|ci/jenkins/webpack-ts|Pack the *nativescript-dev-webpack* plugin and bundle the [template-hello-world-ts](https://github.com/NativeScript/template-hello-world-ts) template app.| -|`ng`|ci/jenkins/webpack-ng|Pack the *nativescript-dev-webpack* plugin and bundle the [template-hello-world-ng](https://github.com/NativeScript/template-hello-world-ng) template app.| -|`groceries`|ci/jenkins/webpack-groceries|Pack the *nativescript-dev-webpack* plugin and bundle the [Groceries](https://github.com/NativeScript/sample-Groceries) app. | -|`sdk`|ci/jenkins/webpack-sdk|Pack the *nativescript-dev-webpack* plugin and bundle the [SDK](https://github.com/NativeScript/nativescript-sdk-examples-ng) app. | -|`testsappng`|ci/jenkins/webpack-testsappng|Pack the *nativescript-dev-webpack* plugin and bundle the [tests-app-ng](https://github.com/NativeScript/tests-app-ng) app. | +|`js`|ci/jenkins/webpack-js|Pack the *@nativescript/webpack* plugin and bundle the [template-hello-world](https://github.com/NativeScript/template-hello-world) template app. | +|`ts`|ci/jenkins/webpack-ts|Pack the *@nativescript/webpack* plugin and bundle the [template-hello-world-ts](https://github.com/NativeScript/template-hello-world-ts) template app.| +|`ng`|ci/jenkins/webpack-ng|Pack the *@nativescript/webpack* plugin and bundle the [template-hello-world-ng](https://github.com/NativeScript/template-hello-world-ng) template app.| +|`groceries`|ci/jenkins/webpack-groceries|Pack the *@nativescript/webpack* plugin and bundle the [Groceries](https://github.com/NativeScript/sample-Groceries) app. | +|`sdk`|ci/jenkins/webpack-sdk|Pack the *@nativescript/webpack* plugin and bundle the [SDK](https://github.com/NativeScript/nativescript-sdk-examples-ng) app. | +|`testsappng`|ci/jenkins/webpack-testsappng|Pack the *@nativescript/webpack* plugin and bundle the [tests-app-ng](https://github.com/NativeScript/tests-app-ng) app. | diff --git a/README.md b/README.md index 0f0183fd..f10eef29 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # NativeScript Webpack -This repository contains the code for the nativescript-dev-webpack plugin which helps in webpacking [NativeScript](https://www.nativescript.org/) apps. +This repository contains the code for the @nativescript/webpack plugin which helps in webpacking [NativeScript](https://www.nativescript.org/) apps. JavaScript code and general asset bundling have been a member of the web developer toolbox for a long time. Tools like Webpack have been providing support for an enjoyable development experience that lets you assemble client-side code from various module sources and formats and then package it together. Most importantly, they allow for page load time optimizations that reduce or parallelize the number of requests a browser makes to the server. @@ -31,7 +31,7 @@ For more details, see the [NativeScript docs for building with webpack](http://d ## Usage ```sh -$ npm install --save-dev nativescript-dev-webpack +$ npm install --save-dev @nativescript/webpack $ tns run android or diff --git a/android-app-components-loader.js b/android-app-components-loader.js index 7f0218b7..c2867a63 100644 --- a/android-app-components-loader.js +++ b/android-app-components-loader.js @@ -6,7 +6,7 @@ module.exports = function (source, map) { const imports = modules.map(convertSlashesInPath) .map(m => `require("${m}");`).join("\n"); const augmentedSource = ` - let applicationCheckPlatform = require("tns-core-modules/application"); + let applicationCheckPlatform = require("@nativescript/core/application"); if (applicationCheckPlatform.android && !global["__snapshot"]) { ${imports} } diff --git a/apply-css-loader.js b/apply-css-loader.js index 41e0f674..04da5491 100644 --- a/apply-css-loader.js +++ b/apply-css-loader.js @@ -26,8 +26,8 @@ module.exports = function (content, map) { } content += ` - const application = require("tns-core-modules/application"); - require("tns-core-modules/ui/styling/style-scope"); + const application = require("@nativescript/core/application"); + require("@nativescript/core/ui/styling/style-scope"); if (typeof exports.forEach === "function") { exports.forEach(cssExport => { diff --git a/bundle-config-loader.ts b/bundle-config-loader.ts index a3e3cdb8..c529df8a 100644 --- a/bundle-config-loader.ts +++ b/bundle-config-loader.ts @@ -20,10 +20,10 @@ const loader: loader.Loader = function (source, map) { if (!registerModules) { registerModules = defaultMatch; - for (const key in ignoredFiles) { + for (const key in ignoredFiles) { registerModules = `(?new RegExp(registerModules); } if (unitTesting) { @@ -34,7 +34,7 @@ const loader: loader.Loader = function (source, map) { const hmr = ` if (module.hot) { - const hmrUpdate = require("nativescript-dev-webpack/hmr").hmrUpdate; + const hmrUpdate = require("@nativescript/webpack/hmr").hmrUpdate; global.__coreModulesLiveSync = global.__onLiveSync; global.__onLiveSync = function () { @@ -54,7 +54,7 @@ const loader: loader.Loader = function (source, map) { } `; - let sourceModule = "tns-core-modules"; + let sourceModule = "@nativescript/core"; if (platform && platform !== "ios" && platform !== "android") { sourceModule = `nativescript-platform-${platform}`; @@ -88,8 +88,8 @@ const loader: loader.Loader = function (source, map) { source = ` require("${ angular ? - 'nativescript-dev-webpack/load-application-css-angular' : - 'nativescript-dev-webpack/load-application-css-regular' + '@nativescript/webpack/load-application-css-angular' : + '@nativescript/webpack/load-application-css-regular' }")(); ${source} `; diff --git a/css2json-loader.spec.ts b/css2json-loader.spec.ts index b5229cd8..95137c75 100644 --- a/css2json-loader.spec.ts +++ b/css2json-loader.spec.ts @@ -52,7 +52,7 @@ describe("css2jsonLoader", () => { it("inlines css2json loader in imports if option is provided", (done) => { const loaderContext = { callback: (error, source: string, map) => { - expect(source).toContain(`global.registerModule("./custom.css", () => require("!nativescript-dev-webpack/css2json-loader?useForImports!./custom.css"))`); + expect(source).toContain(`global.registerModule("./custom.css", () => require("!@nativescript/webpack/css2json-loader?useForImports!./custom.css"))`); expect(source).toContain(`{"type":"declaration","property":"background-color","value":"#7f9"}`); done(); diff --git a/css2json-loader.ts b/css2json-loader.ts index 19f75bfa..dd99d7b4 100644 --- a/css2json-loader.ts +++ b/css2json-loader.ts @@ -4,7 +4,7 @@ import { getOptions, urlToRequest } from "loader-utils"; const betweenQuotesPattern = /('|")(.*?)\1/; const unpackUrlPattern = /url\(([^\)]+)\)/; -const inlineLoader = "!nativescript-dev-webpack/css2json-loader?useForImports!" +const inlineLoader = "!@nativescript/webpack/css2json-loader?useForImports!" const loader: loader.Loader = function (content: string, map) { const options = getOptions(this) || {}; @@ -26,7 +26,7 @@ const loader: loader.Loader = function (content: string, map) { } }); const str = JSON.stringify(ast, (k, v) => k === "position" ? undefined : v); - this.callback(null, `${dependencies.join("\n")}module.exports = ${str};`, map); + this.callback(null, `${dependencies.join("\n")}module.exports = ${str};`); } function getImportRules(ast: Stylesheet): Import[] { diff --git a/demo/AngularApp/app/activity.android.ts b/demo/AngularApp/app/activity.android.ts index c5e8dce9..d8929e31 100644 --- a/demo/AngularApp/app/activity.android.ts +++ b/demo/AngularApp/app/activity.android.ts @@ -1,4 +1,4 @@ -import { setActivityCallbacks, AndroidActivityCallbacks } from "tns-core-modules/ui/frame"; +import { setActivityCallbacks, AndroidActivityCallbacks } from "@nativescript/core/ui/frame"; @JavaProxy("org.myApp.MainActivity") class Activity extends androidx.appcompat.app.AppCompatActivity { diff --git a/demo/AngularApp/app/app.module.ts b/demo/AngularApp/app/app.module.ts index 330039b4..719e38e0 100644 --- a/demo/AngularApp/app/app.module.ts +++ b/demo/AngularApp/app/app.module.ts @@ -1,5 +1,5 @@ import { NgModule, NO_ERRORS_SCHEMA } from "@angular/core"; -import { NativeScriptModule } from "nativescript-angular/nativescript.module"; +import { NativeScriptModule } from "@nativescript/angular"; import { AppRoutingModule } from "./app.routing"; import { AppComponent } from "./app.component"; @@ -10,10 +10,10 @@ import { ItemDetailComponent } from "./item/item-detail.component"; // import { PlayfulSpirit } from "./directive"; // Uncomment and add to NgModule imports if you need to use two-way binding -// import { NativeScriptFormsModule } from "nativescript-angular/forms"; +// import { NativeScriptFormsModule } from "@nativescript/angular"; // Uncomment and add to NgModule imports if you need to use the HTTP wrapper -// import { NativeScriptHttpModule } from "nativescript-angular/http"; +// import { NativeScriptHttpModule } from "@nativescript/angular"; @NgModule({ bootstrap: [ diff --git a/demo/AngularApp/app/app.routing.ts b/demo/AngularApp/app/app.routing.ts index 05b5fdef..53ebd347 100644 --- a/demo/AngularApp/app/app.routing.ts +++ b/demo/AngularApp/app/app.routing.ts @@ -1,5 +1,5 @@ import { NgModule } from "@angular/core"; -import { NativeScriptRouterModule } from "nativescript-angular/router"; +import { NativeScriptRouterModule } from "@nativescript/angular"; import { Routes } from "@angular/router"; import { ItemsComponent } from "./item/items.component"; @@ -11,7 +11,7 @@ const routes: Routes = [ { path: "item/:id", component: ItemDetailComponent }, { path: "ninjas", - loadChildren: "./ninjas/ninjas.module#NinjasModule", + loadChildren: () => import("./ninjas/ninjas.module").then(m => m.NinjasModule) }, ]; diff --git a/demo/AngularApp/app/main.aot.ts b/demo/AngularApp/app/main.aot.ts deleted file mode 100644 index d5ff77a7..00000000 --- a/demo/AngularApp/app/main.aot.ts +++ /dev/null @@ -1,7 +0,0 @@ -// this import should be first in order to load some required settings (like globals and reflect-metadata) -import { platformNativeScript } from "nativescript-angular/platform-static"; - -// "./app.module.ngfactory" is a dynamically generated module when compiled with AoT. -import { AppModuleNgFactory } from "./app.module.ngfactory"; - -platformNativeScript().bootstrapModuleFactory(AppModuleNgFactory); diff --git a/demo/AngularApp/app/main.ts b/demo/AngularApp/app/main.ts index 6804026f..e79c6cba 100644 --- a/demo/AngularApp/app/main.ts +++ b/demo/AngularApp/app/main.ts @@ -1,5 +1,5 @@ // this import should be first in order to load some required settings (like globals and reflect-metadata) -import { platformNativeScriptDynamic } from "nativescript-angular/platform"; +import { platformNativeScript } from "@nativescript/angular"; import { AppModule } from "./app.module"; -platformNativeScriptDynamic().bootstrapModule(AppModule); +platformNativeScript().bootstrapModule(AppModule); diff --git a/demo/AngularApp/app/ninjas/details/ninja.module.ts b/demo/AngularApp/app/ninjas/details/ninja.module.ts index dd67895b..f7e814e5 100644 --- a/demo/AngularApp/app/ninjas/details/ninja.module.ts +++ b/demo/AngularApp/app/ninjas/details/ninja.module.ts @@ -1,6 +1,5 @@ -import { NativeScriptCommonModule } from "nativescript-angular/common"; +import { NativeScriptCommonModule, NativeScriptRouterModule } from "@nativescript/angular"; import { NgModule, NO_ERRORS_SCHEMA } from "@angular/core"; -import { NativeScriptRouterModule } from "nativescript-angular/router"; import { NinjaComponent } from "./ninja.component"; import { routes } from "./ninja.routes"; diff --git a/demo/AngularApp/app/ninjas/ninjas.module.ts b/demo/AngularApp/app/ninjas/ninjas.module.ts index 403b5a8d..57d82d08 100644 --- a/demo/AngularApp/app/ninjas/ninjas.module.ts +++ b/demo/AngularApp/app/ninjas/ninjas.module.ts @@ -1,6 +1,5 @@ -import { NativeScriptCommonModule } from "nativescript-angular/common"; +import { NativeScriptCommonModule, NativeScriptRouterModule } from "@nativescript/angular"; import { NgModule, NO_ERRORS_SCHEMA } from "@angular/core"; -import { NativeScriptRouterModule } from "nativescript-angular/router"; import { NinjasComponent } from "./ninjas.component"; import { routes } from "./ninjas.routes"; diff --git a/demo/AngularApp/package.json b/demo/AngularApp/package.json index 013838ca..900191cf 100644 --- a/demo/AngularApp/package.json +++ b/demo/AngularApp/package.json @@ -13,23 +13,23 @@ } }, "dependencies": { - "@angular/common": "8.2.0", - "@angular/compiler": "8.2.0", - "@angular/core": "8.2.0", - "@angular/forms": "8.2.0", - "@angular/platform-browser": "8.2.0", - "@angular/platform-browser-dynamic": "8.2.0", - "@angular/router": "8.2.0", - "nativescript-angular": "next", + "@angular/common": "~10.0.0", + "@angular/compiler": "~10.0.0", + "@angular/core": "~10.0.0", + "@angular/forms": "~10.0.0", + "@angular/platform-browser": "~10.0.0", + "@angular/platform-browser-dynamic": "~10.0.0", + "@angular/router": "~10.0.0", + "@nativescript/angular": "next", + "@nativescript/core": "next", "nativescript-theme-core": "~1.0.2", "reflect-metadata": "~0.1.8", - "rxjs": "^6.3.3", - "tns-core-modules": "next", - "zone.js": "^0.9.1" + "rxjs": "^6.5.5", + "zone.js": "^0.10.3" }, "devDependencies": { - "@angular/compiler-cli": "8.2.0", - "@ngtools/webpack": "8.2.0", + "@angular/compiler-cli": "~10.0.0", + "@ngtools/webpack": "~10.0.0", "@types/chai": "~4.1.7", "@types/mocha": "~5.2.5", "@types/node": "~10.12.18", @@ -42,12 +42,12 @@ "chai": "4.2.0", "mochawesome": "~3.1.2", "nativescript-dev-appium": "next", - "nativescript-dev-webpack": "next", + "@nativescript/webpack": "next", "node-sass": "^4.12.0", - "typescript": "~3.5.3" + "typescript": "~3.9.0" }, "scripts": { - "setup": "npm pack ../../ && npm i -D nativescript-dev-webpack*.tgz", + "setup": "npm pack ../../ && npm i -D nativescript-webpack*.tgz", "e2e": "tsc -p e2e && mocha --opts ../config/mocha.opts --recursive e2e --appiumCapsLocation ../config/appium.capabilities.json", "compile-tests": "tsc -p e2e --watch" } diff --git a/demo/AngularApp/tsconfig.json b/demo/AngularApp/tsconfig.json index daaafd10..2e643e07 100644 --- a/demo/AngularApp/tsconfig.json +++ b/demo/AngularApp/tsconfig.json @@ -15,10 +15,6 @@ "paths": { "~/*": [ "app/*" - ], - "*": [ - "./node_modules/tns-core-modules/*", - "./node_modules/*" ] } }, diff --git a/demo/JavaScriptApp/app/activity.android.js b/demo/JavaScriptApp/app/activity.android.js index 953672d0..e0be2211 100644 --- a/demo/JavaScriptApp/app/activity.android.js +++ b/demo/JavaScriptApp/app/activity.android.js @@ -1,4 +1,4 @@ -const frame = require("tns-core-modules/ui/frame"); +const frame = require("@nativescript/core/ui/frame"); const superProto = androidx.appcompat.app.AppCompatActivity.prototype; androidx.appcompat.app.AppCompatActivity.extend("org.myApp.MainActivity", { diff --git a/demo/JavaScriptApp/app/app.js b/demo/JavaScriptApp/app/app.js index 88f57ca6..f93d212e 100644 --- a/demo/JavaScriptApp/app/app.js +++ b/demo/JavaScriptApp/app/app.js @@ -4,7 +4,7 @@ You can use this file to perform app-level initialization, but the primary purpose of the file is to pass control to the app’s first module. */ -var application = require("tns-core-modules/application"); +var application = require("@nativescript/core/application"); application.run({ moduleName: "app-root" }); diff --git a/demo/JavaScriptApp/app/main-page.android.js b/demo/JavaScriptApp/app/main-page.android.js index 70a0ab21..32f1142b 100644 --- a/demo/JavaScriptApp/app/main-page.android.js +++ b/demo/JavaScriptApp/app/main-page.android.js @@ -1,4 +1,4 @@ -var frameModule = require("tns-core-modules/ui/frame"); +var frameModule = require("@nativescript/core/ui/frame"); var createViewModel = require("./main-view-model").createViewModel; function onNavigatingTo(args) { diff --git a/demo/JavaScriptApp/app/main-page.ios.js b/demo/JavaScriptApp/app/main-page.ios.js index 094ffd4a..e685f1ca 100644 --- a/demo/JavaScriptApp/app/main-page.ios.js +++ b/demo/JavaScriptApp/app/main-page.ios.js @@ -1,4 +1,4 @@ -var frameModule = require("tns-core-modules/ui/frame"); +var frameModule = require("@nativescript/core/ui/frame"); var createViewModel = require("./main-view-model").createViewModel; function onNavigatingTo(args) { diff --git a/demo/JavaScriptApp/app/main-view-model.js b/demo/JavaScriptApp/app/main-view-model.js index 20ab082e..fbc6e0f2 100644 --- a/demo/JavaScriptApp/app/main-view-model.js +++ b/demo/JavaScriptApp/app/main-view-model.js @@ -1,4 +1,4 @@ -var Observable = require("tns-core-modules/data/observable").Observable; +var Observable = require("@nativescript/core/data/observable").Observable; function getMessage(counter) { if (counter <= 0) { diff --git a/demo/JavaScriptApp/app/references.d.ts b/demo/JavaScriptApp/app/references.d.ts deleted file mode 100644 index db28a5d7..00000000 --- a/demo/JavaScriptApp/app/references.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// Enable smart suggestions and completions in Visual Studio Code JavaScript projects. diff --git a/demo/JavaScriptApp/package.json b/demo/JavaScriptApp/package.json index 1a04d9af..a607582d 100644 --- a/demo/JavaScriptApp/package.json +++ b/demo/JavaScriptApp/package.json @@ -14,7 +14,7 @@ }, "dependencies": { "nativescript-theme-core": "~1.0.2", - "tns-core-modules": "next" + "@nativescript/core": "~6.5.8" }, "devDependencies": { "@types/chai": "~4.1.7", @@ -28,11 +28,11 @@ "mocha": "~5.2.0", "mochawesome": "~3.1.2", "nativescript-dev-appium": "next", - "nativescript-dev-webpack": "next", + "@nativescript/webpack": "next", "node-sass": "4.12.0" }, "scripts": { - "setup": "npm pack ../../ && npm i -D nativescript-dev-webpack*.tgz", + "setup": "npm pack ../../ && npm i -D nativescript-webpack*.tgz", "e2e": "mocha --opts ../config/mocha.opts --recursive e2e --appiumCapsLocation ../config/appium.capabilities.json" } } diff --git a/demo/TypeScriptApp/app/activity.android.ts b/demo/TypeScriptApp/app/activity.android.ts index 29f7ad66..a0350bc6 100644 --- a/demo/TypeScriptApp/app/activity.android.ts +++ b/demo/TypeScriptApp/app/activity.android.ts @@ -1,4 +1,4 @@ -import {setActivityCallbacks, AndroidActivityCallbacks} from "tns-core-modules/ui/frame"; +import {setActivityCallbacks, AndroidActivityCallbacks} from "@nativescript/core/ui/frame"; @JavaProxy("org.myApp.MainActivity") class Activity extends androidx.appcompat.app.AppCompatActivity { diff --git a/demo/TypeScriptApp/app/app.ts b/demo/TypeScriptApp/app/app.ts index d8db4e32..441166d4 100644 --- a/demo/TypeScriptApp/app/app.ts +++ b/demo/TypeScriptApp/app/app.ts @@ -4,7 +4,7 @@ You can use this file to perform app-level initialization, but the primary purpose of the file is to pass control to the app’s first module. */ -import * as app from 'tns-core-modules/application'; +import * as app from '@nativescript/core/application'; app.run({ moduleName: "app-root" }); diff --git a/demo/TypeScriptApp/app/main-page.android.ts b/demo/TypeScriptApp/app/main-page.android.ts index 62554095..6bed9723 100644 --- a/demo/TypeScriptApp/app/main-page.android.ts +++ b/demo/TypeScriptApp/app/main-page.android.ts @@ -4,10 +4,7 @@ a code-behind file. The code-behind is a great place to place your view logic, and to set up your page’s data binding. */ -import { EventData } from 'tns-core-modules/data/observable'; -import { Page } from 'tns-core-modules/ui/page'; -import { Label } from 'tns-core-modules/ui/label'; -import * as frameModule from 'tns-core-modules/ui/frame'; +import { EventData, Page, Label, Frame } from '@nativescript/core'; import { HelloWorldModel } from './main-view-model'; export function onNavigatingTo(args: EventData) { @@ -17,6 +14,6 @@ export function onNavigatingTo(args: EventData) { } export function goToSecondPage(args) { - var topmost = frameModule.topmost(); + var topmost = Frame.topmost(); topmost.navigate("views/second-page"); } diff --git a/demo/TypeScriptApp/app/main-page.ios.ts b/demo/TypeScriptApp/app/main-page.ios.ts index 02f3fa4c..3fd4807b 100644 --- a/demo/TypeScriptApp/app/main-page.ios.ts +++ b/demo/TypeScriptApp/app/main-page.ios.ts @@ -4,11 +4,8 @@ a code-behind file. The code-behind is a great place to place your view logic, and to set up your page’s data binding. */ -import { EventData } from 'tns-core-modules/data/observable'; -import { Page } from 'tns-core-modules/ui/page'; +import { EventData, Page, Label, Frame } from '@nativescript/core'; import { HelloWorldModel } from './main-view-model'; -import { Label } from 'tns-core-modules/ui/label'; -import * as frameModule from 'tns-core-modules/ui/frame'; // Event handler for Page "navigatingTo" event attached in main-page.xml export function onNavigatingTo(args: EventData) { @@ -35,6 +32,6 @@ export function onNavigatingTo(args: EventData) { } export function goToSecondPage(args) { - var topmost = frameModule.topmost(); + var topmost = Frame.topmost(); topmost.navigate("views/second-page"); } diff --git a/demo/TypeScriptApp/app/main-view-model.ts b/demo/TypeScriptApp/app/main-view-model.ts index 56936641..1bd87ae1 100644 --- a/demo/TypeScriptApp/app/main-view-model.ts +++ b/demo/TypeScriptApp/app/main-view-model.ts @@ -1,4 +1,4 @@ -import {Observable} from 'tns-core-modules/data/observable'; +import {Observable} from '@nativescript/core'; export class HelloWorldModel extends Observable { diff --git a/demo/TypeScriptApp/package.json b/demo/TypeScriptApp/package.json index dd8eee9e..de112e38 100644 --- a/demo/TypeScriptApp/package.json +++ b/demo/TypeScriptApp/package.json @@ -14,7 +14,7 @@ }, "dependencies": { "nativescript-theme-core": "~1.0.2", - "tns-core-modules": "next" + "@nativescript/core": "~6.5.8" }, "devDependencies": { "@types/chai": "~4.1.7", @@ -28,12 +28,12 @@ "chai": "4.2.0", "mochawesome": "~3.1.2", "nativescript-dev-appium": "next", - "nativescript-dev-webpack": "next", + "@nativescript/webpack": "next", "typescript": "~3.4.1", "node-sass": "^4.12.0" }, "scripts": { - "setup": "npm pack ../../ && npm i -D nativescript-dev-webpack*.tgz", + "setup": "npm pack ../../ && npm i -D nativescript-webpack*.tgz", "e2e": "tsc -p e2e && mocha --opts ../config/mocha.opts --recursive e2e --appiumCapsLocation ../config/appium.capabilities.json", "compile-tests": "tsc -p e2e --watch" } diff --git a/demo/TypeScriptApp/tsconfig.json b/demo/TypeScriptApp/tsconfig.json index 4e5e97a3..88478922 100644 --- a/demo/TypeScriptApp/tsconfig.json +++ b/demo/TypeScriptApp/tsconfig.json @@ -12,10 +12,6 @@ ], "baseUrl": ".", "paths": { - "*": [ - "./node_modules/tns-core-modules/*", - "./node_modules/*" - ], "~/*": [ "app/*" ] diff --git a/hmr/hmr-update.ts b/hmr/hmr-update.ts index e4778c33..2c4eeb08 100644 --- a/hmr/hmr-update.ts +++ b/hmr/hmr-update.ts @@ -1,5 +1,5 @@ import * as hot from "../hot"; -import { knownFolders, path, File } from "tns-core-modules/file-system"; +import { knownFolders, path, File } from "@nativescript/core"; declare const __webpack_require__: any; diff --git a/index.js b/index.js index 766d4af4..e37fa059 100644 --- a/index.js +++ b/index.js @@ -180,7 +180,7 @@ exports.processAppComponents = (appComponents, platform) => { exports.getUserDefinedEntries = (entries, platform) => { const userDefinedEntries = []; for (const entry in entries) { - if (entry !== "bundle" && entry !== "tns_modules/tns-core-modules/inspector_modules") { + if (entry !== "bundle" && entry !== "tns_modules/@nativescript/core/inspector_modules") { userDefinedEntries.push(entries[entry].replace(`.${platform}`, "")); } } diff --git a/load-application-css.js b/load-application-css.js index 36ce05ec..da51519c 100644 --- a/load-application-css.js +++ b/load-application-css.js @@ -1,6 +1,6 @@ module.exports = function (loadModuleFn) { - const application = require("tns-core-modules/application"); - require("tns-core-modules/ui/styling/style-scope"); + const application = require("@nativescript/core/application"); + require("@nativescript/core/ui/styling/style-scope"); loadModuleFn(); diff --git a/package.json b/package.json index 3892593c..dd500698 100644 --- a/package.json +++ b/package.json @@ -1,12 +1,13 @@ { - "name": "nativescript-dev-webpack", - "version": "1.5.0", + "name": "@nativescript/webpack", + "version": "2.0.0-alpha.3", "main": "index", - "description": "", - "homepage": "http://www.telerik.com", - "bugs": "http://www.telerik.com", + "description": "Webpack plugin for NativeScript", + "homepage": "https://nativescript.org", + "bugs": "https://github.com/NativeScript/NativeScript/issues", "contributors": [ - "Hristo Deshev " + "Hristo Deshev ", + "NativeScript " ], "nativescript": { "hooks": [ @@ -28,6 +29,7 @@ "url": "https://github.com/NativeScript/nativescript-dev-webpack.git" }, "scripts": { + "clean": "npx rimraf node_modules package-lock.json && npm i", "tsc": "tsc", "postinstall": "node postinstall.js", "preuninstall": "node preuninstall.js", @@ -47,57 +49,56 @@ "generate-android-snapshot": "./bin/generate-android-snapshot" }, "dependencies": { - "@angular-devkit/core": "8.2.0", - "clean-webpack-plugin": "~1.0.0", - "copy-webpack-plugin": "~4.6.0", - "css": "2.2.1", - "css-loader": "~2.1.1", - "escape-string-regexp": "1.0.5", - "fork-ts-checker-webpack-plugin": "2.0.0", - "global-modules-path": "2.0.0", - "loader-utils": "^1.2.3", - "minimatch": "3.0.4", - "nativescript-hook": "0.2.4", - "nativescript-worker-loader": "~0.10.0", - "properties-reader": "0.3.1", + "@angular-devkit/core": "~10.0.0", + "clean-webpack-plugin": "~3.0.0", + "copy-webpack-plugin": "~6.0.2", + "css": "~2.2.1", + "css-loader": "~3.6.0", + "escape-string-regexp": "~4.0.0", + "fork-ts-checker-webpack-plugin": "~5.0.0", + "global-modules-path": "~2.3.0", + "loader-utils": "~2.0.0", + "minimatch": "~3.0.4", + "@nativescript/hook": "~1.0.0", + "nativescript-worker-loader": "~0.12.0", + "properties-reader": "~2.0.0", "proxy-lib": "0.4.0", - "raw-loader": "~0.5.1", - "request": "2.88.0", - "resolve-url-loader": "~3.0.0", - "sass-loader": "~7.1.0", + "raw-loader": "~4.0.0", + "resolve-url-loader": "~3.1.0", + "sass-loader": "~9.0.0", "sax": "^1.2.4", - "schema-utils": "0.4.5", - "semver": "^6.0.0", + "schema-utils": "~2.7.0", + "semver": "^7.3.0", "shelljs": "~0.8.4", - "tapable": "1.0.0", - "terser": "3.17.0", - "terser-webpack-plugin": "1.2.3", - "ts-loader": "^5.3.1", - "webpack": "~4.27.0", - "webpack-bundle-analyzer": "~3.3.2", - "webpack-cli": "~3.1.1", - "webpack-sources": "~1.3.0" + "tapable": "~1.1.3", + "terser": "~4.8.0", + "terser-webpack-plugin": "~3.0.0", + "ts-loader": "^7.0.0", + "webpack": "~4.43.0", + "webpack-bundle-analyzer": "~3.8.0", + "webpack-cli": "~3.3.12", + "webpack-sources": "~1.4.3" }, "devDependencies": { - "@angular/compiler": "8.2.0", - "@angular/compiler-cli": "8.2.0", - "@istanbuljs/nyc-config-typescript": "^0.1.3", - "@ngtools/webpack": "8.2.0", - "@types/css": "0.0.31", - "@types/jasmine": "^3.3.7", - "@types/loader-utils": "^1.1.3", - "@types/node": "^10.12.12", - "@types/proxyquire": "1.3.28", + "@angular/compiler": "~10.0.0", + "@angular/compiler-cli": "~10.0.0", + "@istanbuljs/nyc-config-typescript": "^1.0.0", + "@ngtools/webpack": "~10.0.0", + "@types/css": "~0.0.31", + "@types/jasmine": "^3.5.11", + "@types/loader-utils": "^2.0.0", + "@types/node": "~14.0.0", + "@types/proxyquire": "~1.3.28", "@types/sax": "^1.2.0", - "@types/semver": "^6.0.0", - "@types/webpack": "^4.4.34", - "conventional-changelog-cli": "^1.3.22", - "jasmine": "^3.2.0", - "jasmine-spec-reporter": "^4.2.1", - "nyc": "^14.1.1", - "proxyquire": "2.1.0", + "@types/semver": "^7.3.0", + "@types/webpack": "^4.41.18", + "conventional-changelog-cli": "~2.0.34", + "jasmine": "^3.5.0", + "jasmine-spec-reporter": "^5.0.2", + "nyc": "^15.1.0", + "proxyquire": "~2.1.0", "source-map-support": "^0.5.13", - "tns-core-modules": "next", - "typescript": "~3.5.3" + "@nativescript/core": "^6.5.8", + "typescript": "~3.9.0" } } diff --git a/plugins/NativeScriptSnapshotPlugin/index.js b/plugins/NativeScriptSnapshotPlugin/index.js index 58b14876..a6780b45 100644 --- a/plugins/NativeScriptSnapshotPlugin/index.js +++ b/plugins/NativeScriptSnapshotPlugin/index.js @@ -50,8 +50,8 @@ exports.NativeScriptSnapshotPlugin = (function () { snapshotEntryContent += ` require("${ options.angular ? - 'nativescript-dev-webpack/load-application-css-angular' : - 'nativescript-dev-webpack/load-application-css-regular' + '@nativescript/webpack/load-application-css-angular' : + '@nativescript/webpack/load-application-css-regular' }")(); `; } diff --git a/plugins/PlatformFSPlugin.ts b/plugins/PlatformFSPlugin.ts index 91daccac..484c7813 100644 --- a/plugins/PlatformFSPlugin.ts +++ b/plugins/PlatformFSPlugin.ts @@ -64,7 +64,7 @@ export function mapFileSystem(args: MapFileSystemArgs): any { const minimatchFileFilters = ignore.map(pattern => { const minimatchFilter = minimatch.filter(pattern); - return file => minimatchFilter(relative(context, file)); + return file => minimatchFilter(relative(context, file), 0, []); }); const isIgnored = file => minimatchFileFilters.some(filter => filter(file)); diff --git a/postinstall.js b/postinstall.js index 1956dcf5..5f6aa010 100644 --- a/postinstall.js +++ b/postinstall.js @@ -1,6 +1,6 @@ "use strict"; -const hook = require("nativescript-hook")(__dirname); +const hook = require("@nativescript/hook")(__dirname); const { compareProjectFiles } = require("./projectFilesManager"); const { getProjectDir } = require("./projectHelpers"); @@ -9,7 +9,7 @@ const fs = require("fs"); const projectDir = getProjectDir(); -// This method is introduced as in version 1.0.0 of nativescript-dev-webpack (compatible and required for NativeScript 6.0.0) +// This method is introduced as in version 1.0.0 of @nativescript/webpack (compatible and required for NativeScript 6.0.0) // we have changed a lot of hooks and old ones are incompatible. This should be automatically handled with preuninstall script of the old version. // However, old versions of nativescript-dev-webpack do not have such logic, so remove them manually on postinstall of the current version. // This logic can be removed later, once most of the projects are migrated to 1.0.0 of the package or later. @@ -49,7 +49,7 @@ if (projectDir) { const installer = require("./installer"); installer.install(); } else { - // We are installing dev dependencies for the nativescript-dev-webpack plugin. - console.log("Skipping postinstall artifacts! We assumed the nativescript-dev-webpack is installing devDependencies"); + // We are installing dev dependencies for the @nativescript/webpack plugin. + console.log("Skipping postinstall artifacts! We assumed the @nativescript/webpack is installing devDependencies"); } diff --git a/preuninstall.js b/preuninstall.js index 8632200f..595329e3 100644 --- a/preuninstall.js +++ b/preuninstall.js @@ -1,6 +1,6 @@ "use strict"; -const hook = require("nativescript-hook")(__dirname); +const hook = require("@nativescript/hook")(__dirname); const { getProjectDir } = require("./projectHelpers"); diff --git a/projectFilesManager.js b/projectFilesManager.js index d033d492..409a95dc 100644 --- a/projectFilesManager.js +++ b/projectFilesManager.js @@ -33,7 +33,7 @@ function compareProjectFiles(projectDir) { const currentTemplate = fs.readFileSync(currentTemplatePath).toString(); const newTemplate = fs.readFileSync(newTemplatePath).toString(); if (newTemplate.replace(/\s/g, '') !== currentTemplate.replace(/\s/g, '')) { - const message = `The current project contains a ${path.basename(currentTemplatePath)} file located at ${currentTemplatePath} that differs from the one in the new version of the nativescript-dev-webpack plugin located at ${newTemplatePath}. Some of the plugin features may not work as expected until you manually update the ${path.basename(currentTemplatePath)} file or automatically update it using "./node_modules/.bin/update-ns-webpack --configs" command.`; + const message = `Note: ${path.basename(currentTemplatePath)} is different than the suggested @nativescript/webpack config at ${newTemplatePath}.\nIf you have build trouble you can update to latest config using "./node_modules/.bin/update-ns-webpack --configs" command.`; console.info(`\x1B[33;1m${message}\x1B[0m`); } } diff --git a/projectHelpers.js b/projectHelpers.js index ca3a24b6..07cc2d5a 100644 --- a/projectHelpers.js +++ b/projectHelpers.js @@ -1,7 +1,7 @@ const { resolve } = require("path"); const fs = require("fs"); -const hook = require("nativescript-hook")(__dirname); +const hook = require("@nativescript/hook")(__dirname); const isTypeScript = ({ projectDir, packageJson } = {}) => { packageJson = packageJson || getPackageJson(projectDir); diff --git a/snapshot/android/utils.js b/snapshot/android/utils.js index 947f0302..193d3352 100644 --- a/snapshot/android/utils.js +++ b/snapshot/android/utils.js @@ -4,7 +4,7 @@ const { join, relative, isAbsolute } = require("path"); const os = require("os"); const { mkdir } = require("shelljs"); -const { get } = require("request"); +// const { get } = require("request"); const { getProxySettings } = require("proxy-lib"); const semver = require("semver"); @@ -66,39 +66,39 @@ function isWindows() { const downloadFile = (url, destinationFilePath, timeout) => new Promise((resolve, reject) => { - getRequestOptions(url, timeout) - .then(options => - get(options) - .on("error", reject) - .pipe(createWriteStream(destinationFilePath, { autoClose: true })) - .on("finish", _ => { - chmodSync(destinationFilePath, 0755); - return resolve(destinationFilePath); - }) - ).catch(reject); + // getRequestOptions(url, timeout) + // .then(options => + // get(options) + // .on("error", reject) + // .pipe(createWriteStream(destinationFilePath, { autoClose: true })) + // .on("finish", _ => { + // chmodSync(destinationFilePath, 0755); + // return resolve(destinationFilePath); + // }) + // ).catch(reject); }); const getJsonFile = url => new Promise((resolve, reject) => { - getRequestOptions(url) - .then(options => - get(options, (error, response, body) => { - if (error) { - return reject(error); - } - - if (!response || response.statusCode !== 200) { - return reject(`Couldn't fetch ${url}! Response:${EOL}${response}`); - } - - try { - const data = JSON.parse(body); - resolve(data); - } catch (error) { - reject(`Couldn't parse json data! Original error:${EOL}${error}`); - } - }) - ).catch(reject); + // getRequestOptions(url) + // .then(options => + // get(options, (error, response, body) => { + // if (error) { + // return reject(error); + // } + + // if (!response || response.statusCode !== 200) { + // return reject(`Couldn't fetch ${url}! Response:${EOL}${response}`); + // } + + // try { + // const data = JSON.parse(body); + // resolve(data); + // } catch (error) { + // reject(`Couldn't parse json data! Original error:${EOL}${error}`); + // } + // }) + // ).catch(reject); }); const getRequestOptions = (url, timeout) => diff --git a/templates/tsconfig.tns.json b/templates/tsconfig.tns.json index 9ce50ed9..a96f6bbc 100644 --- a/templates/tsconfig.tns.json +++ b/templates/tsconfig.tns.json @@ -1,7 +1,7 @@ { "extends": "./tsconfig", "compilerOptions": { - "module": "esNext", + "module": "ESNext", "moduleResolution": "node" } } diff --git a/templates/webpack.angular.js b/templates/webpack.angular.js index f0b43bbe..edd97db3 100644 --- a/templates/webpack.angular.js +++ b/templates/webpack.angular.js @@ -1,356 +1,417 @@ -const { join, relative, resolve, sep, dirname } = require("path"); +const { join, relative, resolve, sep, dirname } = 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 { nsReplaceLazyLoader } = require("nativescript-dev-webpack/transformers/ns-replace-lazy-loader"); -const { nsSupportHmrNg } = require("nativescript-dev-webpack/transformers/ns-support-hmr-ng"); -const { getMainModulePath } = require("nativescript-dev-webpack/utils/ast-utils"); -const { getNoEmitOnErrorFromTSConfig, getCompilerOptionsFromTSConfig } = require("nativescript-dev-webpack/utils/tsconfig-utils"); -const CleanWebpackPlugin = require("clean-webpack-plugin"); -const CopyWebpackPlugin = require("copy-webpack-plugin"); -const { BundleAnalyzerPlugin } = require("webpack-bundle-analyzer"); -const { NativeScriptWorkerPlugin } = require("nativescript-worker-loader/NativeScriptWorkerPlugin"); -const TerserPlugin = require("terser-webpack-plugin"); -const { getAngularCompilerPlugin } = require("nativescript-dev-webpack/plugins/NativeScriptAngularCompilerPlugin"); +const webpack = require('webpack'); +const nsWebpack = require('@nativescript/webpack'); +const nativescriptTarget = require('@nativescript/webpack/nativescript-target'); +const { + nsReplaceLazyLoader +} = require('@nativescript/webpack/transformers/ns-replace-lazy-loader'); +const { + nsSupportHmrNg +} = require('@nativescript/webpack/transformers/ns-support-hmr-ng'); +const { + getMainModulePath +} = require('@nativescript/webpack/utils/ast-utils'); +const { CleanWebpackPlugin } = require('clean-webpack-plugin'); +const CopyWebpackPlugin = require('copy-webpack-plugin'); +const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer'); +const { + NativeScriptWorkerPlugin +} = require('nativescript-worker-loader/NativeScriptWorkerPlugin'); +const TerserPlugin = require('terser-webpack-plugin'); +const { + getAngularCompilerPlugin +} = require('@nativescript/webpack/plugins/NativeScriptAngularCompilerPlugin'); const hashSalt = Date.now().toString(); module.exports = env => { - // Add your custom Activities, Services and other Android app components here. - const appComponents = env.appComponents || []; - appComponents.push(...[ - "tns-core-modules/ui/frame", - "tns-core-modules/ui/frame/activity", - ]); + // Add your custom Activities, Services and other Android app components here. + const appComponents = [ + "@nativescript/core/ui/frame", "@nativescript/core/ui/frame/activity" + ]; - const platform = env && (env.android && "android" || env.ios && "ios" || env.platform); - if (!platform) { - throw new Error("You need to provide a target platform!"); - } - - const AngularCompilerPlugin = getAngularCompilerPlugin(platform); - const projectRoot = __dirname; + const platform = env && ((env.android && 'android') || (env.ios && 'ios')); + if (!platform) { + throw new Error('You need to provide a target platform!'); + } - // Default destination inside platforms//... - const dist = resolve(projectRoot, nsWebpack.getAppPath(platform, projectRoot)); + const AngularCompilerPlugin = getAngularCompilerPlugin(platform); + const projectRoot = __dirname; - const { - // The 'appPath' and 'appResourcesPath' values are fetched from - // the nsconfig.json configuration file. - appPath = "src", - appResourcesPath = "App_Resources", + // Default destination inside platforms//... + const dist = resolve( + projectRoot, + nsWebpack.getAppPath(platform, projectRoot) + ); - // You can provide the following flags when running 'tns run android|ios' - aot, // --env.aot - snapshot, // --env.snapshot, - production, // --env.production - uglify, // --env.uglify - report, // --env.report - sourceMap, // --env.sourceMap - hiddenSourceMap, // --env.hiddenSourceMap - hmr, // --env.hmr, - unitTesting, // --env.unitTesting - verbose, // --env.verbose - snapshotInDocker, // --env.snapshotInDocker - skipSnapshotTools, // --env.skipSnapshotTools - compileSnapshot // --env.compileSnapshot - } = env; + const { + // The 'appPath' and 'appResourcesPath' values are fetched from + // the nsconfig.json configuration file + // when bundling with `tns run android|ios --bundle`. + appPath = 'src', + appResourcesPath = 'App_Resources', - const useLibs = compileSnapshot; - const isAnySourceMapEnabled = !!sourceMap || !!hiddenSourceMap; - const externals = nsWebpack.getConvertedExternals(env.externals); - const appFullPath = resolve(projectRoot, appPath); - const tsConfigName = "tsconfig.tns.json"; - const tsConfigPath = join(__dirname, tsConfigName); - const hasRootLevelScopedModules = nsWebpack.hasRootLevelScopedModules({ projectDir: projectRoot }); - const hasRootLevelScopedAngular = nsWebpack.hasRootLevelScopedAngular({ projectDir: projectRoot }); - let coreModulesPackageName = "tns-core-modules"; - const alias = env.alias || {}; - alias['~'] = appFullPath; - - const compilerOptions = getCompilerOptionsFromTSConfig(tsConfigPath); - if (hasRootLevelScopedModules) { - coreModulesPackageName = "@nativescript/core"; - alias["tns-core-modules"] = coreModulesPackageName; - nsWebpack.processTsPathsForScopedModules({ compilerOptions }); - } + // You can provide the following flags when running 'tns run android|ios' + snapshot, // --env.snapshot, + production, // --env.production + uglify, // --env.uglify + report, // --env.report + sourceMap, // --env.sourceMap + hiddenSourceMap, // --env.hiddenSourceMap + hmr, // --env.hmr, + unitTesting, // --env.unitTesting + verbose, // --env.verbose + ci, // --env.ci + snapshotInDocker, // --env.snapshotInDocker + skipSnapshotTools, // --env.skipSnapshotTools + compileSnapshot // --env.compileSnapshot + } = env; - if (hasRootLevelScopedAngular) { - alias["nativescript-angular"] = "@nativescript/angular"; - nsWebpack.processTsPathsForScopedAngular({ compilerOptions }); - } + const useLibs = compileSnapshot; + const isAnySourceMapEnabled = !!sourceMap || !!hiddenSourceMap; + const externals = nsWebpack.getConvertedExternals(env.externals); + const appFullPath = resolve(projectRoot, appPath); + const appResourcesFullPath = resolve(projectRoot, appResourcesPath); + const tsConfigName = 'tsconfig.tns.json'; + const entryModule = `${nsWebpack.getEntryModule(appFullPath, platform)}.ts`; + const entryPath = `.${sep}${entryModule}`; + const entries = { bundle: entryPath }; + const areCoreModulesExternal = + Array.isArray(env.externals) && + env.externals.some(e => e.indexOf('@nativescript') > -1); + if (platform === 'ios' && !areCoreModulesExternal) { + entries['tns_modules/@nativescript/core/inspector_modules'] = + 'inspector_modules'; + } - const appResourcesFullPath = resolve(projectRoot, appResourcesPath); - const entryModule = `${nsWebpack.getEntryModule(appFullPath, platform)}.ts`; - const entryPath = `.${sep}${entryModule}`; - const entries = env.entries || {}; - entries.bundle = entryPath; + const ngCompilerTransformers = []; + const additionalLazyModuleResources = []; - const areCoreModulesExternal = Array.isArray(env.externals) && env.externals.some(e => e.indexOf("tns-core-modules") > -1); - if (platform === "ios" && !areCoreModulesExternal) { - entries["tns_modules/tns-core-modules/inspector_modules"] = "inspector_modules"; - }; + const copyIgnore = { ignore: [`${relative(appPath, appResourcesFullPath)}/**`] }; + const copyTargets = [ + { from: 'assets/**', noErrorOnMissing: true, globOptions: { dot: false, ...copyIgnore } }, + { from: 'fonts/**', noErrorOnMissing: true, globOptions: { dot: false, ...copyIgnore } }, + ]; - const ngCompilerTransformers = []; - const additionalLazyModuleResources = []; - if (aot) { - ngCompilerTransformers.push(nsReplaceBootstrap); - } + if (!production) { + // for development purposes only + // for example, include mock json folder + // copyTargets.push({ from: 'tools/mockdata', to: 'assets/mockdata' }); if (hmr) { - ngCompilerTransformers.push(nsSupportHmrNg); + ngCompilerTransformers.push(nsSupportHmrNg); } + } - // when "@angular/core" is external, it's not included in the bundles. In this way, it will be used - // directly from node_modules and the Angular modules loader won't be able to resolve the lazy routes - // fixes https://github.com/NativeScript/nativescript-cli/issues/4024 - if (env.externals && env.externals.indexOf("@angular/core") > -1) { - const appModuleRelativePath = getMainModulePath(resolve(appFullPath, entryModule), tsConfigName); - if (appModuleRelativePath) { - const appModuleFolderPath = dirname(resolve(appFullPath, appModuleRelativePath)); - // include the lazy loader inside app module - ngCompilerTransformers.push(nsReplaceLazyLoader); - // include the new lazy loader path in the allowed ones - additionalLazyModuleResources.push(appModuleFolderPath); - } + // when "@angular/core" is external, it's not included in the bundles. In this way, it will be used + // directly from node_modules and the Angular modules loader won't be able to resolve the lazy routes + // fixes https://github.com/NativeScript/nativescript-cli/issues/4024 + if (env.externals && env.externals.indexOf('@angular/core') > -1) { + const appModuleRelativePath = getMainModulePath( + resolve(appFullPath, entryModule), + tsConfigName + ); + if (appModuleRelativePath) { + const appModuleFolderPath = dirname( + resolve(appFullPath, appModuleRelativePath) + ); + // include the lazy loader inside app module + ngCompilerTransformers.push(nsReplaceLazyLoader); + // include the new lazy loader path in the allowed ones + additionalLazyModuleResources.push(appModuleFolderPath); } + } - const ngCompilerPlugin = new AngularCompilerPlugin({ - hostReplacementPaths: nsWebpack.getResolver([platform, "tns"]), - platformTransformers: ngCompilerTransformers.map(t => t(() => ngCompilerPlugin, resolve(appFullPath, entryModule), projectRoot)), - mainPath: join(appFullPath, entryModule), - tsConfigPath, - skipCodeGeneration: !aot, - sourceMap: !!isAnySourceMapEnabled, - additionalLazyModuleResources: additionalLazyModuleResources, - compilerOptions: { paths: compilerOptions.paths } - }); + const ngCompilerPlugin = new AngularCompilerPlugin({ + hostReplacementPaths: nsWebpack.getResolver([platform, 'tns']), + platformTransformers: ngCompilerTransformers.map(t => + t(() => ngCompilerPlugin, resolve(appFullPath, entryModule), projectRoot) + ), + mainPath: join(appFullPath, entryModule), + tsConfigPath: join(__dirname, tsConfigName), + skipCodeGeneration: false, + sourceMap: !!isAnySourceMapEnabled, + additionalLazyModuleResources: additionalLazyModuleResources + }); - let sourceMapFilename = nsWebpack.getSourceMapFilename(hiddenSourceMap, __dirname, dist); + let sourceMapFilename = nsWebpack.getSourceMapFilename( + hiddenSourceMap, + __dirname, + dist + ); - const itemsToClean = [`${dist}/**/*`]; - if (platform === "android") { - itemsToClean.push(`${join(projectRoot, "platforms", "android", "app", "src", "main", "assets", "snapshots")}`); - itemsToClean.push(`${join(projectRoot, "platforms", "android", "app", "build", "configurations", "nativescript-android-snapshot")}`); - } + const itemsToClean = [`${dist}/**/*`]; + if (platform === 'android') { + itemsToClean.push( + `${join( + projectRoot, + 'platforms', + 'android', + 'app', + 'src', + 'main', + 'assets', + 'snapshots' + )}` + ); + itemsToClean.push( + `${join( + projectRoot, + 'platforms', + 'android', + 'app', + 'build', + 'configurations', + 'nativescript-android-snapshot' + )}` + ); + } - const noEmitOnErrorFromTSConfig = getNoEmitOnErrorFromTSConfig(join(projectRoot, tsConfigName)); + nsWebpack.processAppComponents(appComponents, platform); + const config = { + mode: production ? 'production' : 'development', + context: appFullPath, + externals, + watchOptions: { + ignored: [ + appResourcesFullPath, + // Don't watch hidden files + '**/.*' + ] + }, + target: nativescriptTarget, + entry: entries, + output: { + pathinfo: false, + path: dist, + sourceMapFilename, + libraryTarget: 'commonjs2', + filename: '[name].js', + globalObject: 'global', + hashSalt + }, + resolve: { + extensions: ['.ts', '.js', '.scss', '.css'], + // Resolve {N} system modules from @nativescript/core + modules: [ + resolve(__dirname, 'node_modules/@nativescript/core'), + resolve(__dirname, 'node_modules'), + 'node_modules/@nativescript/core', + 'node_modules' + ], + alias: { + '~': appFullPath, + "tns-core-modules": "@nativescript/core", + "nativescript-angular": "@nativescript/angular" + }, + symlinks: true + }, + resolveLoader: { + symlinks: false + }, + node: { + // Disable node shims that conflict with NativeScript + http: false, + timers: false, + setImmediate: false, + fs: 'empty', + __dirname: false + }, + devtool: hiddenSourceMap + ? 'hidden-source-map' + : sourceMap + ? 'inline-source-map' + : 'none', + optimization: { + runtimeChunk: 'single', + splitChunks: { + cacheGroups: { + vendor: { + name: 'vendor', + chunks: 'all', + test: (module, chunks) => { + const moduleName = module.nameForCondition + ? module.nameForCondition() + : ''; + return ( + /[\\/]node_modules[\\/]/.test(moduleName) || + appComponents.some(comp => comp === moduleName) + ); + }, + enforce: true + } + } + }, + minimize: !!uglify, + minimizer: [ + new TerserPlugin({ + parallel: true, + cache: !ci, + sourceMap: isAnySourceMapEnabled, + terserOptions: { + output: { + comments: false, + semicolons: !isAnySourceMapEnabled + }, + compress: { + // The Android SBG has problems parsing the output + // when these options are enabled + collapse_vars: platform !== 'android', + sequences: platform !== 'android', + // custom + drop_console: true, + drop_debugger: true, + ecma: 6, + keep_infinity: platform === 'android', // for Chrome/V8 + reduce_funcs: platform !== 'android', // for Chrome/V8 + global_defs: { + __UGLIFIED__: true + } + }, + // custom + ecma: 6, + safari10: platform !== 'android' + } + }) + ] + }, + module: { + rules: [ + { + include: join(appFullPath, entryPath), + use: [ + // Require all Android app components + platform === 'android' && { + loader: '@nativescript/webpack/android-app-components-loader', + options: { modules: appComponents } + }, - nsWebpack.processAppComponents(appComponents, platform); - const config = { - mode: production ? "production" : "development", - context: appFullPath, - externals, - watchOptions: { - ignored: [ - appResourcesFullPath, - // Don't watch hidden files - "**/.*", - ] - }, - target: nativescriptTarget, - entry: entries, - output: { - pathinfo: false, - path: dist, - sourceMapFilename, - libraryTarget: "commonjs2", - filename: "[name].js", - globalObject: "global", - hashSalt - }, - resolve: { - extensions: [".ts", ".js", ".scss", ".css"], - // Resolve {N} system modules from tns-core-modules - modules: [ - resolve(__dirname, `node_modules/${coreModulesPackageName}`), - resolve(__dirname, "node_modules"), - `node_modules/${coreModulesPackageName}`, - "node_modules", - ], - alias, - symlinks: true + { + loader: '@nativescript/webpack/bundle-config-loader', + options: { + angular: true, + loadCss: !snapshot, // load the application css if in debug mode + unitTesting, + appFullPath, + projectRoot, + ignoredFiles: nsWebpack.getUserDefinedEntries(entries, platform) + } + } + ].filter(loader => !!loader) }, - resolveLoader: { - symlinks: false - }, - node: { - // Disable node shims that conflict with NativeScript - "http": false, - "timers": false, - "setImmediate": false, - "fs": "empty", - "__dirname": false, + + { test: /\.html$|\.xml$/, use: 'raw-loader' }, + + { + test: /[\/|\\]app\.css$/, + use: [ + '@nativescript/webpack/style-hot-loader', + { + loader: "@nativescript/webpack/css2json-loader", + options: { useForImports: true } + }, + ], }, - devtool: hiddenSourceMap ? "hidden-source-map" : (sourceMap ? "inline-source-map" : "none"), - optimization: { - runtimeChunk: "single", - noEmitOnErrors: noEmitOnErrorFromTSConfig, - splitChunks: { - cacheGroups: { - vendor: { - name: "vendor", - chunks: "all", - test: (module, chunks) => { - const moduleName = module.nameForCondition ? module.nameForCondition() : ''; - return /[\\/]node_modules[\\/]/.test(moduleName) || - appComponents.some(comp => comp === moduleName); - }, - enforce: true, - }, - } - }, - minimize: !!uglify, - minimizer: [ - new TerserPlugin({ - parallel: true, - cache: true, - sourceMap: isAnySourceMapEnabled, - terserOptions: { - output: { - comments: false, - semicolons: !isAnySourceMapEnabled - }, - compress: { - // The Android SBG has problems parsing the output - // when these options are enabled - 'collapse_vars': platform !== "android", - sequences: platform !== "android", - } - } - }) - ], + { + test: /[\/|\\]app\.scss$/, + use: [ + '@nativescript/webpack/style-hot-loader', + { + loader: "@nativescript/webpack/css2json-loader", + options: { useForImports: true } + }, + 'sass-loader', + ], }, - module: { - rules: [ - { - include: join(appFullPath, entryPath), - use: [ - // Require all Android app components - platform === "android" && { - loader: "nativescript-dev-webpack/android-app-components-loader", - options: { modules: appComponents } - }, - { - loader: "nativescript-dev-webpack/bundle-config-loader", - options: { - angular: true, - loadCss: !snapshot, // load the application css if in debug mode - unitTesting, - appFullPath, - projectRoot, - ignoredFiles: nsWebpack.getUserDefinedEntries(entries, platform) - } - }, - ].filter(loader => !!loader) - }, - - { test: /\.html$|\.xml$/, use: "raw-loader" }, + // Angular components reference css files and their imports using raw-loader + { test: /\.css$/, exclude: /[\/|\\]app\.css$/, use: 'raw-loader' }, + { + test: /\.scss$/, + exclude: /[\/|\\]app\.scss$/, + use: ['raw-loader', 'resolve-url-loader', 'sass-loader'] + }, - { - test: /[\/|\\]app\.css$/, - use: [ - "nativescript-dev-webpack/style-hot-loader", - { - loader: "nativescript-dev-webpack/css2json-loader", - options: { useForImports: true } - } - ] - }, - { - test: /[\/|\\]app\.scss$/, - use: [ - "nativescript-dev-webpack/style-hot-loader", - { - loader: "nativescript-dev-webpack/css2json-loader", - options: { useForImports: true } - }, - "sass-loader" - ] - }, + { + test: /(?:\.ngfactory\.js|\.ngstyle\.js|\.ts)$/, + use: [ + '@nativescript/webpack/moduleid-compat-loader', + '@nativescript/webpack/lazy-ngmodule-hot-loader', + '@ngtools/webpack' + ] + }, - // Angular components reference css files and their imports using raw-loader - { test: /\.css$/, exclude: /[\/|\\]app\.css$/, use: "raw-loader" }, - { test: /\.scss$/, exclude: /[\/|\\]app\.scss$/, use: ["raw-loader", "resolve-url-loader", "sass-loader"] }, + // Mark files inside `@angular/core` as using SystemJS style dynamic imports. + // Removing this will cause deprecation warnings to appear. + { + test: /[\/\\]@angular[\/\\]core[\/\\].+\.js$/, + parser: { system: true } + } + ] + }, + plugins: [ + // Define useful constants like TNS_WEBPACK + new webpack.DefinePlugin({ + 'global.TNS_WEBPACK': 'true', + process: 'global.process' + }), + // Remove all files from the out dir. + new CleanWebpackPlugin({ + cleanOnceBeforeBuildPatterns: itemsToClean, + verbose: !!verbose + }), + // Copy assets + new CopyWebpackPlugin({ + patterns: copyTargets, + }), + new nsWebpack.GenerateNativeScriptEntryPointsPlugin('bundle'), + // For instructions on how to set up workers with webpack + // check out https://github.com/nativescript/worker-loader + new NativeScriptWorkerPlugin(), + ngCompilerPlugin, + // Does IPC communication with the {N} CLI to notify events when running in watch mode. + new nsWebpack.WatchStateLoggerPlugin() + ] + }; - { - test: /(?:\.ngfactory\.js|\.ngstyle\.js|\.ts)$/, - use: [ - "nativescript-dev-webpack/moduleid-compat-loader", - "nativescript-dev-webpack/lazy-ngmodule-hot-loader", - "@ngtools/webpack", - ] - }, + if (report) { + // Generate report files for bundles content + config.plugins.push( + new BundleAnalyzerPlugin({ + analyzerMode: 'static', + openAnalyzer: false, + generateStatsFile: true, + reportFilename: resolve(projectRoot, 'report', `report.html`), + statsFilename: resolve(projectRoot, 'report', `stats.json`) + }) + ); + } - // Mark files inside `@angular/core` as using SystemJS style dynamic imports. - // Removing this will cause deprecation warnings to appear. - { - test: /[\/\\]@angular[\/\\]core[\/\\].+\.js$/, - parser: { system: true }, - }, - ], - }, - plugins: [ - // Define useful constants like TNS_WEBPACK - new webpack.DefinePlugin({ - "global.TNS_WEBPACK": "true", - "process": "global.process", - }), - // Remove all files from the out dir. - new CleanWebpackPlugin(itemsToClean, { verbose: !!verbose }), - // Copy assets to out dir. Add your own globs as needed. - new CopyWebpackPlugin([ - { from: { glob: "fonts/**" } }, - { from: { glob: "**/*.jpg" } }, - { from: { glob: "**/*.png" } }, - ], { ignore: [`${relative(appPath, appResourcesFullPath)}/**`] }), - new nsWebpack.GenerateNativeScriptEntryPointsPlugin("bundle"), - // For instructions on how to set up workers with webpack - // check out https://github.com/nativescript/worker-loader - new NativeScriptWorkerPlugin(), - ngCompilerPlugin, - // Does IPC communication with the {N} CLI to notify events when running in watch mode. - new nsWebpack.WatchStateLoggerPlugin(), + if (snapshot) { + config.plugins.push( + new nsWebpack.NativeScriptSnapshotPlugin({ + chunk: 'vendor', + angular: true, + requireModules: [ + 'reflect-metadata', + '@angular/platform-browser', + '@angular/core', + '@angular/common', + '@angular/router', + '@nativescript/angular' ], - }; - - if (report) { - // Generate report files for bundles content - config.plugins.push(new BundleAnalyzerPlugin({ - analyzerMode: "static", - openAnalyzer: false, - generateStatsFile: true, - reportFilename: resolve(projectRoot, "report", `report.html`), - statsFilename: resolve(projectRoot, "report", `stats.json`), - })); - } + projectRoot, + webpackConfig: config, + snapshotInDocker, + skipSnapshotTools, + useLibs + }) + ); + } - if (snapshot) { - config.plugins.push(new nsWebpack.NativeScriptSnapshotPlugin({ - chunk: "vendor", - angular: true, - requireModules: [ - "reflect-metadata", - "@angular/platform-browser", - "@angular/core", - "@angular/common", - "@angular/router", - "nativescript-angular/platform-static", - "nativescript-angular/router", - ], - projectRoot, - webpackConfig: config, - snapshotInDocker, - skipSnapshotTools, - useLibs - })); - } - - if (hmr) { - config.plugins.push(new webpack.HotModuleReplacementPlugin()); - } + if (!production && hmr) { + config.plugins.push(new webpack.HotModuleReplacementPlugin()); + } - return config; -}; + return config; +}; \ No newline at end of file diff --git a/templates/webpack.config.spec.ts b/templates/webpack.config.spec.ts index 8d62b062..53cbd439 100644 --- a/templates/webpack.config.spec.ts +++ b/templates/webpack.config.spec.ts @@ -41,18 +41,16 @@ const nativeScriptDevWebpack = { }; const emptyObject = {}; -const FakeAotTransformerFlag = "aot"; const FakeHmrTransformerFlag = "hmr"; const FakeLazyTransformerFlag = "lazy"; const webpackConfigAngular = proxyquire('./webpack.angular', { - 'nativescript-dev-webpack': nativeScriptDevWebpack, - 'nativescript-dev-webpack/nativescript-target': emptyObject, - 'nativescript-dev-webpack/transformers/ns-replace-bootstrap': { nsReplaceBootstrap: () => { return FakeAotTransformerFlag } }, - 'nativescript-dev-webpack/transformers/ns-replace-lazy-loader': { nsReplaceLazyLoader: () => { return FakeLazyTransformerFlag } }, - 'nativescript-dev-webpack/transformers/ns-support-hmr-ng': { nsSupportHmrNg: () => { return FakeHmrTransformerFlag } }, - 'nativescript-dev-webpack/utils/ast-utils': { getMainModulePath: () => { return "fakePath"; } }, - 'nativescript-dev-webpack/utils/tsconfig-utils': { getNoEmitOnErrorFromTSConfig: () => { return false; }, getCompilerOptionsFromTSConfig: () => { return false; } }, - 'nativescript-dev-webpack/plugins/NativeScriptAngularCompilerPlugin': { getAngularCompilerPlugin: () => { return AngularCompilerStub; } }, + '@nativescript/webpack': nativeScriptDevWebpack, + '@nativescript/webpack/nativescript-target': emptyObject, + '@nativescript/webpack/transformers/ns-replace-lazy-loader': { nsReplaceLazyLoader: () => { return FakeLazyTransformerFlag } }, + '@nativescript/webpack/transformers/ns-support-hmr-ng': { nsSupportHmrNg: () => { return FakeHmrTransformerFlag } }, + '@nativescript/webpack/utils/ast-utils': { getMainModulePath: () => { return "fakePath"; } }, + '@nativescript/webpack/utils/tsconfig-utils': { getNoEmitOnErrorFromTSConfig: () => { return false; }, getCompilerOptionsFromTSConfig: () => { return false; } }, + '@nativescript/webpack/plugins/NativeScriptAngularCompilerPlugin': { getAngularCompilerPlugin: () => { return AngularCompilerStub; } }, '@ngtools/webpack': { AngularCompilerPlugin: AngularCompilerStub }, @@ -60,28 +58,28 @@ const webpackConfigAngular = proxyquire('./webpack.angular', { }); const webpackConfigTypeScript = proxyquire('./webpack.typescript', { - 'nativescript-dev-webpack': nativeScriptDevWebpack, - 'nativescript-dev-webpack/nativescript-target': emptyObject, - 'nativescript-dev-webpack/utils/tsconfig-utils': { getNoEmitOnErrorFromTSConfig: () => { return false; }, getCompilerOptionsFromTSConfig: () => { return false; } }, + '@nativescript/webpack': nativeScriptDevWebpack, + '@nativescript/webpack/nativescript-target': emptyObject, + '@nativescript/webpack/utils/tsconfig-utils': { getNoEmitOnErrorFromTSConfig: () => { return false; }, getCompilerOptionsFromTSConfig: () => { return false; } }, 'terser-webpack-plugin': TerserJsStub }); const webpackConfigJavaScript = proxyquire('./webpack.javascript', { - 'nativescript-dev-webpack': nativeScriptDevWebpack, - 'nativescript-dev-webpack/nativescript-target': emptyObject, + '@nativescript/webpack': nativeScriptDevWebpack, + '@nativescript/webpack/nativescript-target': emptyObject, 'terser-webpack-plugin': TerserJsStub }); const webpackConfigVue = proxyquire('./webpack.vue', { - 'nativescript-dev-webpack': nativeScriptDevWebpack, - 'nativescript-dev-webpack/nativescript-target': emptyObject, + '@nativescript/webpack': nativeScriptDevWebpack, + '@nativescript/webpack/nativescript-target': emptyObject, 'vue-loader/lib/plugin': EmptyClass, 'nativescript-vue-template-compiler': emptyObject, 'terser-webpack-plugin': TerserJsStub }); describe('webpack.config.js', () => { - const getInput = (options: { platform: string, aot?: boolean, hmr?: boolean, externals?: string[], sourceMap?: boolean, hiddenSourceMap?: boolean | string }) => { + const getInput = (options: { platform: string, hmr?: boolean, externals?: string[], sourceMap?: boolean, hiddenSourceMap?: boolean | string }) => { const input: any = Object.assign({}, options);; input[options.platform] = true; return input; @@ -121,19 +119,19 @@ describe('webpack.config.js', () => { expect(isCalled).toBe(true, 'Webpack.config.js must use the getConvertedExternals method'); }); - if (platform === "ios") { - it('has inspector_modules entry when tns-core-modules are not externals', () => { - const input = getInput({ platform, externals: ['nativescript-vue'] }); - const config = webpackConfig(input); - expect(config.entry["tns_modules/tns-core-modules/inspector_modules"]).toEqual("inspector_modules"); - }); + // if (platform === "ios") { + // it('has inspector_modules entry when tns-core-modules are not externals', () => { + // const input = getInput({ platform, externals: ['nativescript-vue'] }); + // const config = webpackConfig(input); + // expect(config.entry["tns_modules/@nativescript/core/inspector_modules"]).toEqual("inspector_modules"); + // }); - it('does not have inspector_modules entry when tns-core-modules are externals', () => { - const input = getInput({ platform, externals: ['tns-core-modules'] }); - const config = webpackConfig(input); - expect(config.entry["tns_modules/tns-core-modules/inspector_modules"]).toBeUndefined(); - }); - } + // it('does not have inspector_modules entry when @nativescript/core are externals', () => { + // const input = getInput({ platform, externals: ['@nativescript'] }); + // const config = webpackConfig(input); + // expect(config.entry["tns_modules/@nativescript/core/inspector_modules"]).toBeUndefined(); + // }); + // } [ { @@ -172,17 +170,6 @@ describe('webpack.config.js', () => { expect(angularCompilerOptions.platformTransformers.length).toEqual(0); }); - it("should contain the AOT transformer when the AOT flag is passed", () => { - const input = getInput({ platform, aot: true }); - - webpackConfig(input); - - expect(angularCompilerOptions).toBeDefined(); - expect(angularCompilerOptions.platformTransformers).toBeDefined(); - expect(angularCompilerOptions.platformTransformers.length).toEqual(1); - expect(angularCompilerOptions.platformTransformers[0]).toEqual(FakeAotTransformerFlag); - }); - it("should contain the HMR transformer when the HMR flag is passed", () => { const input = getInput({ platform, hmr: true }); @@ -205,42 +192,6 @@ describe('webpack.config.js', () => { expect(angularCompilerOptions.platformTransformers[0]).toEqual(FakeLazyTransformerFlag); }); - it("should contain the AOT + HMR transformers when the AOT and HMR flags are passed", () => { - const input = getInput({ platform, aot: true, hmr: true }); - - webpackConfig(input); - - expect(angularCompilerOptions).toBeDefined(); - expect(angularCompilerOptions.platformTransformers).toBeDefined(); - expect(angularCompilerOptions.platformTransformers.length).toEqual(2); - expect(angularCompilerOptions.platformTransformers).toContain(FakeAotTransformerFlag); - expect(angularCompilerOptions.platformTransformers).toContain(FakeHmrTransformerFlag); - }); - - it("should set the AOT transformer before the HMR one when the AOT and HMR flags are passed", () => { - const input = getInput({ platform, aot: true, hmr: true }); - - webpackConfig(input); - - expect(angularCompilerOptions).toBeDefined(); - expect(angularCompilerOptions.platformTransformers).toBeDefined(); - expect(angularCompilerOptions.platformTransformers.length).toEqual(2); - expect(angularCompilerOptions.platformTransformers[0]).toEqual(FakeAotTransformerFlag); - expect(angularCompilerOptions.platformTransformers[1]).toEqual(FakeHmrTransformerFlag); - }); - - it("should contain the AOT + Lazy transformers when the AOT flag is passed and @angular/core is an external module", () => { - const input = getInput({ platform, aot: true, externals: ["@angular/core"] }); - - webpackConfig(input); - - expect(angularCompilerOptions).toBeDefined(); - expect(angularCompilerOptions.platformTransformers).toBeDefined(); - expect(angularCompilerOptions.platformTransformers.length).toEqual(2); - expect(angularCompilerOptions.platformTransformers).toContain(FakeAotTransformerFlag); - expect(angularCompilerOptions.platformTransformers).toContain(FakeLazyTransformerFlag); - }); - it("should contain the HMR + Lazy transformers when the HMR flag is passed and @angular/core is an external module", () => { const input = getInput({ platform, hmr: true, externals: ["@angular/core"] }); @@ -253,30 +204,28 @@ describe('webpack.config.js', () => { expect(angularCompilerOptions.platformTransformers).toContain(FakeLazyTransformerFlag); }); - it("should contain the AOT + HMR + Lazy transformers when the AOT and HMR flags are passed and @angular/core is an external module", () => { - const input = getInput({ platform, aot: true, hmr: true, externals: ["@angular/core"] }); + it("should contain the HMR + Lazy transformers when the HMR flags are passed and @angular/core is an external module", () => { + const input = getInput({ platform, hmr: true, externals: ["@angular/core"] }); webpackConfig(input); expect(angularCompilerOptions).toBeDefined(); expect(angularCompilerOptions.platformTransformers).toBeDefined(); - expect(angularCompilerOptions.platformTransformers.length).toEqual(3); - expect(angularCompilerOptions.platformTransformers).toContain(FakeAotTransformerFlag); + expect(angularCompilerOptions.platformTransformers.length).toEqual(2); expect(angularCompilerOptions.platformTransformers).toContain(FakeHmrTransformerFlag); expect(angularCompilerOptions.platformTransformers).toContain(FakeLazyTransformerFlag); }); - it("should contain the AOT + HMR + Lazy transformers in the proper order when the AOT and HMR flags are passed and @angular/core is an external module", () => { - const input = getInput({ platform, aot: true, hmr: true, externals: ["@angular/core"] }); + it("should contain the HMR + Lazy transformers in the proper order when the HMR flags are passed and @angular/core is an external module", () => { + const input = getInput({ platform, hmr: true, externals: ["@angular/core"] }); webpackConfig(input); expect(angularCompilerOptions).toBeDefined(); expect(angularCompilerOptions.platformTransformers).toBeDefined(); - expect(angularCompilerOptions.platformTransformers.length).toEqual(3); - expect(angularCompilerOptions.platformTransformers[0]).toEqual(FakeAotTransformerFlag); - expect(angularCompilerOptions.platformTransformers[1]).toEqual(FakeHmrTransformerFlag); - expect(angularCompilerOptions.platformTransformers[2]).toEqual(FakeLazyTransformerFlag); + expect(angularCompilerOptions.platformTransformers.length).toEqual(2); + expect(angularCompilerOptions.platformTransformers[0]).toEqual(FakeHmrTransformerFlag); + expect(angularCompilerOptions.platformTransformers[1]).toEqual(FakeLazyTransformerFlag); }); }); } @@ -361,29 +310,6 @@ describe('webpack.config.js', () => { expect(config.output.sourceMapFilename).toEqual(join("..", newSourceMapFolder, "[file].map")); }); }); - - describe(`alias for webpack.${type}.js (${platform})`, () => { - it('should add alias when @nativescript/core is at the root of node_modules', () => { - nativeScriptDevWebpack.hasRootLevelScopedModules = () => true; - nativeScriptDevWebpack.hasRootLevelScopedAngular = () => true; - const input = getInput({ platform }); - const config = webpackConfig(input); - expect(config.resolve.alias['tns-core-modules']).toBe('@nativescript/core'); - if (type === 'angular') { - expect(config.resolve.alias['nativescript-angular']).toBe('@nativescript/angular'); - } - }); - it('shouldn\'t add alias when @nativescript/core is not at the root of node_modules', () => { - nativeScriptDevWebpack.hasRootLevelScopedModules = () => false; - nativeScriptDevWebpack.hasRootLevelScopedAngular = () => false; - const input = getInput({ platform }); - const config = webpackConfig(input); - expect(config.resolve.alias['tns-core-modules']).toBeUndefined(); - if (type === 'angular') { - expect(config.resolve.alias['nativescript-angular']).toBeUndefined(); - } - }); - }); }); }); }); \ No newline at end of file diff --git a/templates/webpack.javascript.js b/templates/webpack.javascript.js index 59360c38..74d626ed 100644 --- a/templates/webpack.javascript.js +++ b/templates/webpack.javascript.js @@ -1,9 +1,9 @@ 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 CleanWebpackPlugin = require("clean-webpack-plugin"); +const nsWebpack = require("@nativescript/webpack"); +const nativescriptTarget = require("@nativescript/webpack/nativescript-target"); +const { CleanWebpackPlugin } = require("clean-webpack-plugin"); const CopyWebpackPlugin = require("copy-webpack-plugin"); const { BundleAnalyzerPlugin } = require("webpack-bundle-analyzer"); const { NativeScriptWorkerPlugin } = require("nativescript-worker-loader/NativeScriptWorkerPlugin"); @@ -14,8 +14,8 @@ module.exports = env => { // Add your custom Activities, Services and other android app components here. const appComponents = env.appComponents || []; appComponents.push(...[ - "tns-core-modules/ui/frame", - "tns-core-modules/ui/frame/activity", + "@nativescript/core/ui/frame", + "@nativescript/core/ui/frame/activity", ]); const platform = env && (env.android && "android" || env.ios && "ios" || env.platform); @@ -69,14 +69,16 @@ module.exports = env => { } const appResourcesFullPath = resolve(projectRoot, appResourcesPath); + const copyIgnore = { ignore: [`${relative(appPath, appResourcesFullPath)}/**`] }; + const entryModule = nsWebpack.getEntryModule(appFullPath, platform); const entryPath = `.${sep}${entryModule}.js`; const entries = env.entries || {}; entries.bundle = entryPath; - const areCoreModulesExternal = Array.isArray(env.externals) && env.externals.some(e => e.indexOf("tns-core-modules") > -1); + const areCoreModulesExternal = Array.isArray(env.externals) && env.externals.some(e => e.indexOf("@nativescript") > -1); if (platform === "ios" && !areCoreModulesExternal) { - entries["tns_modules/tns-core-modules/inspector_modules"] = "inspector_modules"; + entries["tns_modules/@nativescript/core/inspector_modules"] = "inspector_modules"; }; let sourceMapFilename = nsWebpack.getSourceMapFilename(hiddenSourceMap, __dirname, dist); @@ -113,7 +115,7 @@ module.exports = env => { }, resolve: { extensions: [".js", ".scss", ".css"], - // Resolve {N} system modules from tns-core-modules + // Resolve {N} system modules from @nativescript/core modules: [ resolve(__dirname, `node_modules/${coreModulesPackageName}`), resolve(__dirname, "node_modules"), @@ -183,12 +185,12 @@ module.exports = env => { use: [ // Require all Android app components platform === "android" && { - loader: "nativescript-dev-webpack/android-app-components-loader", + loader: "@nativescript/webpack/android-app-components-loader", options: { modules: appComponents } }, { - loader: "nativescript-dev-webpack/bundle-config-loader", + loader: "@nativescript/webpack/bundle-config-loader", options: { loadCss: !snapshot, // load the application css if in debug mode unitTesting, @@ -202,20 +204,20 @@ module.exports = env => { { test: /\.(js|css|scss|html|xml)$/, - use: "nativescript-dev-webpack/hmr/hot-loader" + use: "@nativescript/webpack/hmr/hot-loader" }, - { test: /\.(html|xml)$/, use: "nativescript-dev-webpack/xml-namespace-loader" }, + { test: /\.(html|xml)$/, use: "@nativescript/webpack/xml-namespace-loader" }, { test: /\.css$/, - use: "nativescript-dev-webpack/css2json-loader" + use: "@nativescript/webpack/css2json-loader" }, { test: /\.scss$/, use: [ - "nativescript-dev-webpack/css2json-loader", + "@nativescript/webpack/css2json-loader", "sass-loader" ] }, @@ -228,13 +230,19 @@ module.exports = env => { "process": "global.process", }), // Remove all files from the out dir. - new CleanWebpackPlugin(itemsToClean, { verbose: !!verbose }), - // Copy assets to out dir. Add your own globs as needed. - new CopyWebpackPlugin([ - { from: { glob: "fonts/**" } }, - { from: { glob: "**/*.jpg" } }, - { from: { glob: "**/*.png" } }, - ], { ignore: [`${relative(appPath, appResourcesFullPath)}/**`] }), + new CleanWebpackPlugin({ + cleanOnceBeforeBuildPatterns: itemsToClean, + verbose: !!verbose + }), + // Copy assets + new CopyWebpackPlugin({ + patterns: [ + { from: 'assets/**', noErrorOnMissing: true, globOptions: { dot: false, ...copyIgnore } }, + { from: 'fonts/**', noErrorOnMissing: true, globOptions: { dot: false, ...copyIgnore } }, + { from: '**/*.jpg', noErrorOnMissing: true, globOptions: { dot: false, ...copyIgnore } }, + { from: '**/*.png', noErrorOnMissing: true, globOptions: { dot: false, ...copyIgnore } }, + ], + }), new nsWebpack.GenerateNativeScriptEntryPointsPlugin("bundle"), // For instructions on how to set up workers with webpack @@ -264,7 +272,7 @@ module.exports = env => { config.plugins.push(new nsWebpack.NativeScriptSnapshotPlugin({ chunk: "vendor", requireModules: [ - "tns-core-modules/bundle-entry-points", + "@nativescript/core/bundle-entry-points", ], projectRoot, webpackConfig: config, diff --git a/templates/webpack.typescript.js b/templates/webpack.typescript.js index 35c4fe65..eb85af08 100644 --- a/templates/webpack.typescript.js +++ b/templates/webpack.typescript.js @@ -1,10 +1,10 @@ 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 { getNoEmitOnErrorFromTSConfig } = require("nativescript-dev-webpack/utils/tsconfig-utils"); -const CleanWebpackPlugin = require("clean-webpack-plugin"); +const nsWebpack = require("@nativescript/webpack"); +const nativescriptTarget = require("@nativescript/webpack/nativescript-target"); +const { getNoEmitOnErrorFromTSConfig } = require("@nativescript/webpack/utils/tsconfig-utils"); +const { CleanWebpackPlugin } = require("clean-webpack-plugin"); const CopyWebpackPlugin = require("copy-webpack-plugin"); const ForkTsCheckerWebpackPlugin = require('fork-ts-checker-webpack-plugin'); const { BundleAnalyzerPlugin } = require("webpack-bundle-analyzer"); @@ -16,8 +16,8 @@ module.exports = env => { // Add your custom Activities, Services and other Android app components here. const appComponents = env.appComponents || []; appComponents.push(...[ - "tns-core-modules/ui/frame", - "tns-core-modules/ui/frame/activity", + "@nativescript/core/ui/frame", + "@nativescript/core/ui/frame/activity", ]); const platform = env && (env.android && "android" || env.ios && "ios" || env.platform); @@ -72,6 +72,8 @@ module.exports = env => { } const appResourcesFullPath = resolve(projectRoot, appResourcesPath); + const copyIgnore = { ignore: [`${relative(appPath, appResourcesFullPath)}/**`] }; + const entryModule = nsWebpack.getEntryModule(appFullPath, platform); const entryPath = `.${sep}${entryModule}.ts`; const entries = env.entries || {}; @@ -79,9 +81,9 @@ module.exports = env => { const tsConfigPath = resolve(projectRoot, "tsconfig.tns.json"); - const areCoreModulesExternal = Array.isArray(env.externals) && env.externals.some(e => e.indexOf("tns-core-modules") > -1); + const areCoreModulesExternal = Array.isArray(env.externals) && env.externals.some(e => e.indexOf("@nativescript") > -1); if (platform === "ios" && !areCoreModulesExternal) { - entries["tns_modules/tns-core-modules/inspector_modules"] = "inspector_modules"; + entries["tns_modules/@nativescript/core/inspector_modules"] = "inspector_modules"; }; let sourceMapFilename = nsWebpack.getSourceMapFilename(hiddenSourceMap, __dirname, dist); @@ -119,7 +121,7 @@ module.exports = env => { }, resolve: { extensions: [".ts", ".js", ".scss", ".css"], - // Resolve {N} system modules from tns-core-modules + // Resolve {N} system modules from @nativescript/core modules: [ resolve(__dirname, `node_modules/${coreModulesPackageName}`), resolve(__dirname, "node_modules"), @@ -189,12 +191,12 @@ module.exports = env => { use: [ // Require all Android app components platform === "android" && { - loader: "nativescript-dev-webpack/android-app-components-loader", + loader: "@nativescript/webpack/android-app-components-loader", options: { modules: appComponents } }, { - loader: "nativescript-dev-webpack/bundle-config-loader", + loader: "@nativescript/webpack/bundle-config-loader", options: { loadCss: !snapshot, // load the application css if in debug mode unitTesting, @@ -208,20 +210,20 @@ module.exports = env => { { test: /\.(ts|css|scss|html|xml)$/, - use: "nativescript-dev-webpack/hmr/hot-loader" + use: "@nativescript/webpack/hmr/hot-loader" }, - { test: /\.(html|xml)$/, use: "nativescript-dev-webpack/xml-namespace-loader" }, + { test: /\.(html|xml)$/, use: "@nativescript/webpack/xml-namespace-loader" }, { test: /\.css$/, - use: "nativescript-dev-webpack/css2json-loader" + use: "@nativescript/webpack/css2json-loader" }, { test: /\.scss$/, use: [ - "nativescript-dev-webpack/css2json-loader", + "@nativescript/webpack/css2json-loader", "sass-loader" ] }, @@ -252,13 +254,19 @@ module.exports = env => { "process": "global.process", }), // Remove all files from the out dir. - new CleanWebpackPlugin(itemsToClean, { verbose: !!verbose }), - // Copy assets to out dir. Add your own globs as needed. - new CopyWebpackPlugin([ - { from: { glob: "fonts/**" } }, - { from: { glob: "**/*.jpg" } }, - { from: { glob: "**/*.png" } }, - ], { ignore: [`${relative(appPath, appResourcesFullPath)}/**`] }), + new CleanWebpackPlugin({ + cleanOnceBeforeBuildPatterns: itemsToClean, + verbose: !!verbose + }), + // Copy assets + new CopyWebpackPlugin({ + patterns: [ + { from: 'assets/**', noErrorOnMissing: true, globOptions: { dot: false, ...copyIgnore } }, + { from: 'fonts/**', noErrorOnMissing: true, globOptions: { dot: false, ...copyIgnore } }, + { from: '**/*.jpg', noErrorOnMissing: true, globOptions: { dot: false, ...copyIgnore } }, + { from: '**/*.png', noErrorOnMissing: true, globOptions: { dot: false, ...copyIgnore } }, + ], + }), new nsWebpack.GenerateNativeScriptEntryPointsPlugin("bundle"), // For instructions on how to set up workers with webpack // check out https://github.com/nativescript/worker-loader @@ -272,11 +280,15 @@ module.exports = env => { // https://github.com/TypeStrong/ts-loader/blob/ea2fcf925ec158d0a536d1e766adfec6567f5fb4/README.md#faster-builds // https://github.com/TypeStrong/ts-loader/blob/ea2fcf925ec158d0a536d1e766adfec6567f5fb4/README.md#hot-module-replacement new ForkTsCheckerWebpackPlugin({ - tsconfig: tsConfigPath, - async: false, - useTypescriptIncrementalApi: true, - checkSyntacticErrors: true, - memoryLimit: 4096 + async: false, + typescript: { + configFile: tsConfigPath, + memoryLimit: 4096, + diagnosticOptions: { + syntactic: true, + semantic: true + } + } }) ], }; @@ -296,7 +308,7 @@ module.exports = env => { config.plugins.push(new nsWebpack.NativeScriptSnapshotPlugin({ chunk: "vendor", requireModules: [ - "tns-core-modules/bundle-entry-points", + "@nativescript/core/bundle-entry-points", ], projectRoot, webpackConfig: config, diff --git a/templates/webpack.vue.js b/templates/webpack.vue.js index 16339117..453fffd2 100644 --- a/templates/webpack.vue.js +++ b/templates/webpack.vue.js @@ -1,7 +1,7 @@ const { join, relative, resolve, sep } = require("path"); const webpack = require("webpack"); -const CleanWebpackPlugin = require("clean-webpack-plugin"); +const { CleanWebpackPlugin } = require("clean-webpack-plugin"); const CopyWebpackPlugin = require("copy-webpack-plugin"); const { BundleAnalyzerPlugin } = require("webpack-bundle-analyzer"); const TerserPlugin = require("terser-webpack-plugin"); @@ -9,8 +9,8 @@ const TerserPlugin = require("terser-webpack-plugin"); const VueLoaderPlugin = require('vue-loader/lib/plugin'); const NsVueTemplateCompiler = require("nativescript-vue-template-compiler"); -const nsWebpack = require("nativescript-dev-webpack"); -const nativescriptTarget = require("nativescript-dev-webpack/nativescript-target"); +const nsWebpack = require("@nativescript/webpack"); +const nativescriptTarget = require("@nativescript/webpack/nativescript-target"); const { NativeScriptWorkerPlugin } = require("nativescript-worker-loader/NativeScriptWorkerPlugin"); const hashSalt = Date.now().toString(); @@ -18,8 +18,8 @@ module.exports = env => { // Add your custom Activities, Services and other android app components here. const appComponents = env.appComponents || []; appComponents.push(...[ - "tns-core-modules/ui/frame", - "tns-core-modules/ui/frame/activity", + "@nativescript/core/ui/frame", + "@nativescript/core/ui/frame/activity", ]); const platform = env && (env.android && "android" || env.ios && "ios" || env.platform); @@ -78,14 +78,16 @@ module.exports = env => { const appResourcesFullPath = resolve(projectRoot, appResourcesPath); + const copyIgnore = { ignore: [`${relative(appPath, appResourcesFullPath)}/**`] }; + const entryModule = nsWebpack.getEntryModule(appFullPath, platform); const entryPath = `.${sep}${entryModule}`; const entries = env.entries || {}; entries.bundle = entryPath; - const areCoreModulesExternal = Array.isArray(env.externals) && env.externals.some(e => e.indexOf("tns-core-modules") > -1); + const areCoreModulesExternal = Array.isArray(env.externals) && env.externals.some(e => e.indexOf("@nativescript") > -1); if (platform === "ios" && !areCoreModulesExternal) { - entries["tns_modules/tns-core-modules/inspector_modules"] = "inspector_modules"; + entries["tns_modules/@nativescript/core/inspector_modules"] = "inspector_modules"; }; console.log(`Bundling application for entryPath ${entryPath}...`); @@ -123,7 +125,7 @@ module.exports = env => { }, resolve: { extensions: [".vue", ".ts", ".js", ".scss", ".css"], - // Resolve {N} system modules from tns-core-modules + // Resolve {N} system modules from @nativescript/core modules: [ resolve(__dirname, `node_modules/${coreModulesPackageName}`), resolve(__dirname, "node_modules"), @@ -193,12 +195,12 @@ module.exports = env => { use: [ // Require all Android app components platform === "android" && { - loader: "nativescript-dev-webpack/android-app-components-loader", + loader: "@nativescript/webpack/android-app-components-loader", options: { modules: appComponents }, }, { - loader: "nativescript-dev-webpack/bundle-config-loader", + loader: "@nativescript/webpack/bundle-config-loader", options: { registerPages: true, // applicable only for non-angular apps loadCss: !snapshot, // load the application css if in debug mode @@ -213,9 +215,9 @@ module.exports = env => { { test: /[\/|\\]app\.css$/, use: [ - 'nativescript-dev-webpack/style-hot-loader', + '@nativescript/webpack/style-hot-loader', { - loader: "nativescript-dev-webpack/css2json-loader", + loader: "@nativescript/webpack/css2json-loader", options: { useForImports: true } }, ], @@ -223,9 +225,9 @@ module.exports = env => { { test: /[\/|\\]app\.scss$/, use: [ - 'nativescript-dev-webpack/style-hot-loader', + '@nativescript/webpack/style-hot-loader', { - loader: "nativescript-dev-webpack/css2json-loader", + loader: "@nativescript/webpack/css2json-loader", options: { useForImports: true } }, 'sass-loader', @@ -235,8 +237,8 @@ module.exports = env => { test: /\.css$/, exclude: /[\/|\\]app\.css$/, use: [ - 'nativescript-dev-webpack/style-hot-loader', - 'nativescript-dev-webpack/apply-css-loader.js', + '@nativescript/webpack/style-hot-loader', + '@nativescript/webpack/apply-css-loader.js', { loader: "css-loader", options: { url: false } }, ], }, @@ -244,8 +246,8 @@ module.exports = env => { test: /\.scss$/, exclude: /[\/|\\]app\.scss$/, use: [ - 'nativescript-dev-webpack/style-hot-loader', - 'nativescript-dev-webpack/apply-css-loader.js', + '@nativescript/webpack/style-hot-loader', + '@nativescript/webpack/apply-css-loader.js', { loader: "css-loader", options: { url: false } }, 'sass-loader', ], @@ -285,13 +287,18 @@ module.exports = env => { "process": "global.process" }), // Remove all files from the out dir. - new CleanWebpackPlugin(itemsToClean, { verbose: !!verbose }), - // Copy assets to out dir. Add your own globs as needed. - new CopyWebpackPlugin([ - { from: { glob: "fonts/**" } }, - { from: { glob: "**/*.+(jpg|png)" } }, - { from: { glob: "assets/**/*" } }, - ], { ignore: [`${relative(appPath, appResourcesFullPath)}/**`] }), + new CleanWebpackPlugin({ + cleanOnceBeforeBuildPatterns: itemsToClean, + verbose: !!verbose + }), + // Copy assets + new CopyWebpackPlugin({ + patterns: [ + { from: 'assets/**', noErrorOnMissing: true, globOptions: { dot: false, ...copyIgnore } }, + { from: 'fonts/**', noErrorOnMissing: true, globOptions: { dot: false, ...copyIgnore } }, + { from: '**/*.+(jpg|png)', noErrorOnMissing: true, globOptions: { dot: false, ...copyIgnore } } + ], + }), new nsWebpack.GenerateNativeScriptEntryPointsPlugin("bundle"), // For instructions on how to set up workers with webpack // check out https://github.com/nativescript/worker-loader @@ -309,14 +316,14 @@ module.exports = env => { config.module.rules.push( { test: /-page\.js$/, - use: "nativescript-dev-webpack/script-hot-loader" + use: "@nativescript/webpack/script-hot-loader" }, { test: /\.(html|xml)$/, - use: "nativescript-dev-webpack/markup-hot-loader" + use: "@nativescript/webpack/markup-hot-loader" }, - { test: /\.(html|xml)$/, use: "nativescript-dev-webpack/xml-namespace-loader" } + { test: /\.(html|xml)$/, use: "@nativescript/webpack/xml-namespace-loader" } ); } @@ -335,7 +342,7 @@ module.exports = env => { config.plugins.push(new nsWebpack.NativeScriptSnapshotPlugin({ chunk: "vendor", requireModules: [ - "tns-core-modules/bundle-entry-points", + "@nativescript/core/bundle-entry-points", ], projectRoot, webpackConfig: config, diff --git a/transformers/ns-replace-bootstrap.spec.ts b/transformers/ns-replace-bootstrap.spec.ts deleted file mode 100644 index 88cbea16..00000000 --- a/transformers/ns-replace-bootstrap.spec.ts +++ /dev/null @@ -1,137 +0,0 @@ -import { tags } from '@angular-devkit/core'; -import { createTypescriptContext, transformTypescript } from "@ngtools/webpack/src/transformers"; -import { nsReplaceBootstrap } from './ns-replace-bootstrap'; -import { AngularCompilerPlugin } from '@ngtools/webpack'; - -describe('@ngtools/webpack transformers', () => { - describe('replace_bootstrap', () => { - it('should replace bootstrap', () => { - const input = tags.stripIndent` - import { platformNativeScriptDynamic } from "nativescript-angular/platform"; - import { AppModule } from "./app.module"; - - platformNativeScriptDynamic().bootstrapModule(AppModule); - `; - - const output = tags.stripIndent` - import * as __NgCli_bootstrap_1_1 from "nativescript-angular/platform-static"; - import * as __NgCli_bootstrap_2_1 from "./app/app.module.ngfactory"; - - __NgCli_bootstrap_1_1.platformNativeScript().bootstrapModuleFactory(__NgCli_bootstrap_2_1.AppModuleNgFactory); - `; - - const { program, compilerHost } = createTypescriptContext(input); - const projectDir = "/project/src/"; - const appModule = `${projectDir}app/app.module`; - const ngCompiler = { - typeChecker: program.getTypeChecker(), - entryModule: { - path: appModule, - className: 'AppModule', - }, - }; - const transformer = nsReplaceBootstrap(() => ngCompiler, appModule, projectDir); - const result = transformTypescript(undefined, [transformer], program, compilerHost); - - expect(tags.oneLine`${result}`).toEqual(tags.oneLine`${output}`); - }); - - it('should replace bootstrap and don`t use factories when Ivy is enabled', () => { - const input = tags.stripIndent` - import { platformNativeScriptDynamic } from "nativescript-angular/platform"; - import { AppModule } from "./app/app.module"; - - platformNativeScriptDynamic().bootstrapModule(AppModule); - `; - - const output = tags.stripIndent` - import * as __NgCli_bootstrap_1_1 from "nativescript-angular/platform-static"; - import * as __NgCli_bootstrap_2_1 from "./app/app.module"; - - __NgCli_bootstrap_1_1.platformNativeScript().bootstrapModule(__NgCli_bootstrap_2_1.AppModule); - `; - - const { program, compilerHost } = createTypescriptContext(input); - const projectDir = "/project/src/"; - const appModule = `${projectDir}app/app.module`; - const ngCompiler: any = { - _compilerOptions: { - enableIvy: true - }, - typeChecker: program.getTypeChecker(), - entryModule: { - path: appModule, - className: 'AppModule', - }, - }; - const transformer = nsReplaceBootstrap(() => ngCompiler, appModule, projectDir); - const result = transformTypescript(undefined, [transformer], program, compilerHost); - - expect(tags.oneLine`${result}`).toEqual(tags.oneLine`${output}`); - }); - - it('should replace bootstrap when barrel files are used', () => { - const input = tags.stripIndent` - import { platformNativeScriptDynamic } from "nativescript-angular/platform"; - import { AppModule } from './app'; - - platformNativeScriptDynamic().bootstrapModule(AppModule); - `; - - const output = tags.stripIndent` - import * as __NgCli_bootstrap_1_1 from "nativescript-angular/platform-static"; - import * as __NgCli_bootstrap_2_1 from "./app/app.module.ngfactory"; - - __NgCli_bootstrap_1_1.platformNativeScript().bootstrapModuleFactory(__NgCli_bootstrap_2_1.AppModuleNgFactory); - `; - - const { program, compilerHost } = createTypescriptContext(input); - const projectDir = "/project/src/"; - const appModule = `${projectDir}app/app.module`; - const ngCompiler = { - typeChecker: program.getTypeChecker(), - entryModule: { - path: appModule, - className: 'AppModule', - }, - }; - const transformer = nsReplaceBootstrap(() => ngCompiler, appModule, projectDir); - const result = transformTypescript(undefined, [transformer], program, compilerHost); - - expect(tags.oneLine`${result}`).toEqual(tags.oneLine`${output}`); - }); - - it('should always import platform nativescript first', () => { - const input = tags.stripIndent` - import { platformNativeScriptDynamic } from "nativescript-angular/platform"; - import { AppModule } from "./app.module"; - import "./shared/kinvey.common"; - - platformNativeScriptDynamic().bootstrapModule(AppModule); - `; - - const output = tags.stripIndent` - import * as __NgCli_bootstrap_1_1 from "nativescript-angular/platform-static"; - import * as __NgCli_bootstrap_2_1 from "./app/app.module.ngfactory"; - import "./shared/kinvey.common"; - - __NgCli_bootstrap_1_1.platformNativeScript().bootstrapModuleFactory(__NgCli_bootstrap_2_1.AppModuleNgFactory); - `; - - const { program, compilerHost } = createTypescriptContext(input); - const projectDir = "/project/src/"; - const appModule = `${projectDir}app/app.module`; - const ngCompiler = { - typeChecker: program.getTypeChecker(), - entryModule: { - path: appModule, - className: 'AppModule', - }, - }; - const transformer = nsReplaceBootstrap(() => ngCompiler, appModule, projectDir); - const result = transformTypescript(undefined, [transformer], program, compilerHost); - - expect(tags.oneLine`${result}`).toEqual(tags.oneLine`${output}`); - }); - }); -}); diff --git a/transformers/ns-replace-bootstrap.ts b/transformers/ns-replace-bootstrap.ts deleted file mode 100644 index 59f06fee..00000000 --- a/transformers/ns-replace-bootstrap.ts +++ /dev/null @@ -1,126 +0,0 @@ -import { dirname, relative } from 'path'; -import * as ts from 'typescript'; -import { - StandardTransform, - TransformOperation, - collectDeepNodes, - insertStarImport, - ReplaceNodeOperation, - makeTransform, - getFirstNode -} from "@ngtools/webpack/src/transformers"; -import { - getExpressionName -} from "../utils/ast-utils"; -import { AngularCompilerPlugin } from '@ngtools/webpack'; -import { getResolvedEntryModule } from "../utils/transformers-utils"; - -export function nsReplaceBootstrap(getNgCompiler: () => AngularCompilerPlugin, entryPath: string, projectDir: string): ts.TransformerFactory { - 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(); - // TODO: use something public when available - const enableIvy = (ngCompiler)._compilerOptions && (ngCompiler)._compilerOptions.enableIvy; - const entryModule = getResolvedEntryModule(ngCompiler, projectDir); - - if (!shouldTransform(sourceFile.fileName) || !entryModule) { - return ops; - } - - // Find all identifiers. - const entryModuleIdentifiers = collectDeepNodes(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 bootstrapCallExpr = entryModuleIdentifier.parent as ts.CallExpression; - - if (bootstrapCallExpr.expression.kind !== ts.SyntaxKind.PropertyAccessExpression) { - return; - } - - const bootstrapPropAccessExpr = bootstrapCallExpr.expression as ts.PropertyAccessExpression; - - if (bootstrapPropAccessExpr.name.text !== 'bootstrapModule' - || bootstrapPropAccessExpr.expression.kind !== ts.SyntaxKind.CallExpression) { - return; - } - - const nsPlatformCallExpr = bootstrapPropAccessExpr.expression as ts.CallExpression; - if (!(getExpressionName(nsPlatformCallExpr.expression) === 'platformNativeScriptDynamic')) { - return; - } - - const idPlatformNativeScript = ts.createUniqueName('__NgCli_bootstrap_1'); - const idNgFactory = ts.createUniqueName('__NgCli_bootstrap_2'); - - const firstNode = getFirstNode(sourceFile); - - const factoryClassName = enableIvy ? entryModule.className : entryModule.className + 'NgFactory'; - const factoryModulePath = enableIvy ? normalizedEntryModulePath : normalizedEntryModulePath + '.ngfactory'; - - const newBootstrapPropAccessExpr = ts.getMutableClone(bootstrapPropAccessExpr); - const newNsPlatformCallExpr = ts.getMutableClone(bootstrapPropAccessExpr.expression) as ts.CallExpression; - newNsPlatformCallExpr.expression = ts.createPropertyAccess(idPlatformNativeScript, 'platformNativeScript'); - newBootstrapPropAccessExpr.expression = newNsPlatformCallExpr; - newBootstrapPropAccessExpr.name = - enableIvy ? ts.createIdentifier("bootstrapModule") : ts.createIdentifier("bootstrapModuleFactory"); - - const newBootstrapCallExpr = ts.getMutableClone(bootstrapCallExpr); - newBootstrapCallExpr.expression = newBootstrapPropAccessExpr; - newBootstrapCallExpr.arguments = ts.createNodeArray([ - ts.createPropertyAccess(idNgFactory, ts.createIdentifier(factoryClassName)) - ]); - - ops.push( - // Insert an import of the {N} Angular static bootstrap module in the beginning of the file: - // import * as __NgCli_bootstrap_2 from "nativescript-angular/platform-static"; - ...insertStarImport( - sourceFile, - idPlatformNativeScript, - 'nativescript-angular/platform-static', - firstNode, - true, - ), - - // Insert an import of the module factory in the beginning of the file: - // import * as __NgCli_bootstrap_1 from "./app.module.ngfactory"; - ...insertStarImport( - sourceFile, - idNgFactory, - factoryModulePath, - firstNode, - true, - ), - - // Replace the bootstrap call expression. For example: - // from: platformNativeScriptDynamic().bootstrapModule(AppModule); - // to: platformNativeScript().bootstrapModuleFactory(__NgCli_bootstrap_2.AppModuleNgFactory); - new ReplaceNodeOperation(sourceFile, bootstrapCallExpr, newBootstrapCallExpr), - ); - }); - - return ops; - }; - - return makeTransform(standardTransform, getTypeChecker); -} diff --git a/transformers/ns-replace-lazy-loader.spec.ts b/transformers/ns-replace-lazy-loader.spec.ts index cdf49df6..9e6b5e68 100644 --- a/transformers/ns-replace-lazy-loader.spec.ts +++ b/transformers/ns-replace-lazy-loader.spec.ts @@ -1,9 +1,9 @@ import { tags } from "@angular-devkit/core"; -import { createTypescriptContext, transformTypescript } from "@ngtools/webpack/src/transformers"; +import { createTypescriptContext, transformTypescript } from "@ngtools/webpack/src/transformers/spec_helpers"; import { nsReplaceLazyLoader, NgLazyLoaderCode, getConfigObjectSetupCode } from "./ns-replace-lazy-loader"; import { AngularCompilerPlugin } from "@ngtools/webpack"; -describe("@ngtools/webpack transformers", () => { +xdescribe("@ngtools/webpack transformers", () => { describe("ns-replace-lazy-loader", () => { const configObjectName = "testIdentifier"; const configObjectSetupCode = getConfigObjectSetupCode(configObjectName, "providers", "NgModuleFactoryLoader", "{ provide: nsNgCoreImport_Generated.NgModuleFactoryLoader, useClass: NSLazyModulesLoader_Generated }"); @@ -12,7 +12,7 @@ describe("@ngtools/webpack transformers", () => { name: "should add providers and NgModuleFactoryLoader when providers is missing", rawAppModule: ` import { NgModule } from "@angular/core"; - import { NativeScriptModule } from "nativescript-angular/nativescript.module"; + import { NativeScriptModule } from "@nativescript/angular"; import { AppComponent } from "./app.component"; @NgModule({ @@ -30,7 +30,7 @@ describe("@ngtools/webpack transformers", () => { `, transformedAppModule: ` import * as tslib_1 from "tslib"; import { NgModule } from "@angular/core"; - import { NativeScriptModule } from "nativescript-angular/nativescript.module"; + import { NativeScriptModule } from "@nativescript/angular"; import { AppComponent } from "./app.component"; ${NgLazyLoaderCode} let AppModule = class AppModule { }; @@ -47,7 +47,7 @@ describe("@ngtools/webpack transformers", () => { name: "should add providers and NgModuleFactoryLoader when providers is missing and decomposition is used", rawAppModule: ` import { NgModule } from "@angular/core"; - import { NativeScriptModule } from "nativescript-angular/nativescript.module"; + import { NativeScriptModule } from "@nativescript/angular"; import { AppComponent } from "./app.component"; const declarationsArray = [AppComponent]; @@ -66,7 +66,7 @@ describe("@ngtools/webpack transformers", () => { `, transformedAppModule: ` import * as tslib_1 from "tslib"; import { NgModule } from "@angular/core"; - import { NativeScriptModule } from "nativescript-angular/nativescript.module"; + import { NativeScriptModule } from "@nativescript/angular"; import { AppComponent } from "./app.component"; ${NgLazyLoaderCode} const declarationsArray = [AppComponent]; @@ -84,7 +84,7 @@ describe("@ngtools/webpack transformers", () => { name: "should add NgModuleFactoryLoader when the providers array is empty", rawAppModule: ` import { NgModule } from "@angular/core"; - import { NativeScriptModule } from "nativescript-angular/nativescript.module"; + import { NativeScriptModule } from "@nativescript/angular"; import { AppComponent } from "./app.component"; @NgModule({ @@ -103,7 +103,7 @@ describe("@ngtools/webpack transformers", () => { `, transformedAppModule: ` import * as tslib_1 from "tslib"; import { NgModule } from "@angular/core"; - import { NativeScriptModule } from "nativescript-angular/nativescript.module"; + import { NativeScriptModule } from "@nativescript/angular"; import { AppComponent } from "./app.component"; ${NgLazyLoaderCode} let AppModule = class AppModule { }; @@ -120,7 +120,7 @@ describe("@ngtools/webpack transformers", () => { name: "should add NgModuleFactoryLoader at the end when the providers array is containing other providers", rawAppModule: ` import { NgModule } from "@angular/core"; - import { NativeScriptModule } from "nativescript-angular/nativescript.module"; + import { NativeScriptModule } from "@nativescript/angular"; import { AppComponent } from "./app.component"; @NgModule({ bootstrap: [ @@ -138,7 +138,7 @@ describe("@ngtools/webpack transformers", () => { `, transformedAppModule: ` import * as tslib_1 from "tslib"; import { NgModule } from "@angular/core"; - import { NativeScriptModule } from "nativescript-angular/nativescript.module"; + import { NativeScriptModule } from "@nativescript/angular"; import { AppComponent } from "./app.component"; ${NgLazyLoaderCode} let AppModule = class AppModule { }; @@ -155,7 +155,7 @@ describe("@ngtools/webpack transformers", () => { name: "should NOT add NgModuleFactoryLoader when it's already defined", rawAppModule: ` import { NgModule } from "@angular/core"; - import { NativeScriptModule } from "nativescript-angular/nativescript.module"; + import { NativeScriptModule } from "@nativescript/angular"; import { AppComponent } from "./app.component"; @NgModule({ @@ -174,7 +174,7 @@ describe("@ngtools/webpack transformers", () => { `, transformedAppModule: ` import * as tslib_1 from "tslib"; import { NgModule } from "@angular/core"; - import { NativeScriptModule } from "nativescript-angular/nativescript.module"; + import { NativeScriptModule } from "@nativescript/angular"; import { AppComponent } from "./app.component"; let AppModule = class AppModule { }; AppModule = tslib_1.__decorate([ NgModule({ diff --git a/transformers/ns-support-hmr-ng.spec.ts b/transformers/ns-support-hmr-ng.spec.ts index 4e873808..619e229e 100644 --- a/transformers/ns-support-hmr-ng.spec.ts +++ b/transformers/ns-support-hmr-ng.spec.ts @@ -1,15 +1,14 @@ import { tags } from "@angular-devkit/core"; -import { createTypescriptContext, transformTypescript } from "@ngtools/webpack/src/transformers"; -import { nsReplaceBootstrap } from './ns-replace-bootstrap'; +import { createTypescriptContext, transformTypescript } from "@ngtools/webpack/src/transformers/spec_helpers"; import { nsSupportHmrNg, getHmrOptionsCode, getAcceptMainModuleCode, GeneratedDynamicAppOptions } from "./ns-support-hmr-ng"; import { AngularCompilerPlugin } from "@ngtools/webpack"; describe("@ngtools/webpack transformers", () => { describe("ns-support-hmr-ng", () => { const nsFactoryImportName = `__NgCli_bootstrap_2_1`; - const handleHmrPlatformDynamicImport = `import * as nativescript_angular_platform_Generated from "nativescript-angular/platform";`; - const handleHmrPlatformStaticImport = `import * as nativescript_angular_platform_Generated from "nativescript-angular/platform-static";`; - const handleAotPlatformStaticImport = `import * as __NgCli_bootstrap_1_1 from "nativescript-angular/platform-static";`; + const handleHmrPlatformDynamicImport = `import * as nativescript_angular_platform_Generated from "@nativescript/angular";`; + const handleHmrPlatformStaticImport = `import * as nativescript_angular_platform_Generated from "@nativescript/angular";`; + const handleAotPlatformStaticImport = `import * as __NgCli_bootstrap_1_1 from "@nativescript/angular";`; const handleAotNgFactoryImport = `import * as ${nsFactoryImportName} from "./test-file.ts.ngfactory";`; const handleHmrOptionsDeclaration = `var ${GeneratedDynamicAppOptions} = {};`; const nsStaticPlatformCall = `nativescript_angular_platform_Generated.platformNativeScript`; @@ -22,314 +21,23 @@ describe("@ngtools/webpack transformers", () => { return `Object.assign(${currentAppOptionsString || "{}"}, ${GeneratedDynamicAppOptions})` }; const defaultAppOptions = getAppOptions(); - const testCases = [{ - name: "should handle HMR when platformNativeScriptDynamic is called without arguments", - rawFile: ` - import { platformNativeScriptDynamic } from "nativescript-angular/platform"; - import { AppModule } from "./app/app.module"; - platformNativeScriptDynamic().bootstrapModule(AppModule); - `, - transformedFile: ` - ${handleHmrPlatformDynamicImport} - import { AppModule } from "./app/app.module"; - - ${handleHmrOptionsDeclaration} - ${handleHmrOptionsCode} - ${acceptMainModuleCode} - - ${nsDynamicPlatformCall}(${defaultAppOptions}).bootstrapModule(AppModule); - `, - transformedFileWithAot: ` - ${handleHmrPlatformStaticImport} - ${handleAotPlatformStaticImport} - ${handleAotNgFactoryImport} - - ${handleHmrOptionsDeclaration} - ${handleHmrOptionsAotCode} - ${acceptMainModuleAotCode} - - ${nsStaticPlatformCall}(${defaultAppOptions}).bootstrapModuleFactory(${nsFactoryImportName}.AppModuleNgFactory); - ` - }, + const testCases = [ { name: "should not handle HMR when the AppModule import cannot be found", rawFile: ` - import { platformNativeScriptDynamic } from "nativescript-angular/platform"; - platformNativeScriptDynamic().bootstrapModule(SyntaxErrorModule); - `, - transformedFile: ` - import { platformNativeScriptDynamic } from "nativescript-angular/platform"; - platformNativeScriptDynamic().bootstrapModule(SyntaxErrorModule); - `, - transformedFileWithAot: ` - import { platformNativeScriptDynamic } from "nativescript-angular/platform"; - platformNativeScriptDynamic().bootstrapModule(SyntaxErrorModule); - ` - }, - { - name: "(known limitation) should not handle HMR when the platformNativeScriptDynamic method is renamed", - rawFile: ` - import { platformNativeScriptDynamic as x } from "nativescript-angular/platform"; - x().bootstrapModule(SyntaxErrorModule); - `, - transformedFile: ` - import { platformNativeScriptDynamic as x } from "nativescript-angular/platform"; - x().bootstrapModule(SyntaxErrorModule); - `, - transformedFileWithAot: ` - import { platformNativeScriptDynamic as x } from "nativescript-angular/platform"; - x().bootstrapModule(SyntaxErrorModule); - ` - }, - { - name: "(known limitation) should not handle HMR when the bootstrapModule method is renamed", - rawFile: ` - import { platformNativeScriptDynamic } from "nativescript-angular/platform"; - - const x = platformNativeScriptDynamic().bootstrapModule; - x(SyntaxErrorModule); - `, - transformedFile: ` - import { platformNativeScriptDynamic } from "nativescript-angular/platform"; - - const x = platformNativeScriptDynamic().bootstrapModule; - x(SyntaxErrorModule); - `, - transformedFileWithAot: ` - import { platformNativeScriptDynamic } from "nativescript-angular/platform"; - - const x = platformNativeScriptDynamic().bootstrapModule; - x(SyntaxErrorModule); - ` - }, - { - name: "should handle HMR when AOT is manually configured", - rawFile: ` - import { platformNativeScript } from "nativescript-angular/platform-static"; - import { AppModuleNgFactory } from "./app/app.module.ngfactory"; - platformNativeScript().bootstrapModuleFactory(AppModuleNgFactory); - `, - transformedFile: ` - ${handleHmrPlatformStaticImport} - import { AppModuleNgFactory } from "./app/app.module.ngfactory"; - - ${handleHmrOptionsDeclaration} - ${getHmrOptionsCode("AppModuleNgFactory", "./app/app.module.ngfactory")} - ${getAcceptMainModuleCode("./app/app.module.ngfactory")} - - ${nsStaticPlatformCall}(${defaultAppOptions}).bootstrapModuleFactory(AppModuleNgFactory); - `, - transformedFileWithAot: ` - ${handleHmrPlatformStaticImport} - import { AppModuleNgFactory } from "./app/app.module.ngfactory"; - - ${handleHmrOptionsDeclaration} - ${getHmrOptionsCode("AppModuleNgFactory", "./app/app.module.ngfactory")} - ${getAcceptMainModuleCode("./app/app.module.ngfactory")} - - ${nsStaticPlatformCall}(${defaultAppOptions}).bootstrapModuleFactory(AppModuleNgFactory); - ` - }, - { - name: "should handle HMR when platformNativeScriptDynamic is called without arguments and non default app module", - customAppModuleName: "CustomModule", - rawFile: ` - import { platformNativeScriptDynamic } from "nativescript-angular/platform"; - import { CustomModule } from "./custom/custom.module"; - platformNativeScriptDynamic().bootstrapModule(CustomModule); - `, - transformedFile: ` - ${handleHmrPlatformDynamicImport} - import { CustomModule } from "./custom/custom.module"; - - ${handleHmrOptionsDeclaration} - ${getHmrOptionsCode("CustomModule", "./custom/custom.module")} - ${getAcceptMainModuleCode("./custom/custom.module")} - - ${nsDynamicPlatformCall}(${defaultAppOptions}).bootstrapModule(CustomModule); - `, - transformedFileWithAot: ` - ${handleHmrPlatformStaticImport} - ${handleAotPlatformStaticImport} - ${handleAotNgFactoryImport} - - ${handleHmrOptionsDeclaration} - ${getHmrOptionsCode("CustomModuleNgFactory", "./test-file.ts.ngfactory")} - ${getAcceptMainModuleCode("./test-file.ts.ngfactory")} - - ${nsStaticPlatformCall}(${defaultAppOptions}).bootstrapModuleFactory(${nsFactoryImportName}.CustomModuleNgFactory); - ` - }, - { - name: "should handle HMR when platformNativeScriptDynamic is called from * import", - rawFile: ` - import * as nsNgPlatform from "nativescript-angular/platform"; - import { AppModule } from "./app/app.module"; - nsNgPlatform.platformNativeScriptDynamic().bootstrapModule(AppModule); - `, - transformedFile: ` - ${handleHmrPlatformDynamicImport} - import { AppModule } from "./app/app.module"; - - ${handleHmrOptionsDeclaration} - ${handleHmrOptionsCode} - ${acceptMainModuleCode} - - ${nsDynamicPlatformCall}(${defaultAppOptions}).bootstrapModule(AppModule); - `, - transformedFileWithAot: ` - ${handleHmrPlatformStaticImport} - ${handleAotPlatformStaticImport} - ${handleAotNgFactoryImport} - - ${handleHmrOptionsDeclaration} - ${handleHmrOptionsAotCode} - ${acceptMainModuleAotCode} - - ${nsStaticPlatformCall}(${defaultAppOptions}).bootstrapModuleFactory(${nsFactoryImportName}.AppModuleNgFactory); - ` - }, - { - name: "should handle HMR when platformNativeScriptDynamic is called with inline appOptions", - rawFile: ` - import { platformNativeScriptDynamic } from "nativescript-angular/platform"; - import { AppModule } from "./app/app.module"; - platformNativeScriptDynamic({ bootInExistingPage: true }).bootstrapModule(AppModule); - `, - transformedFile: ` - ${handleHmrPlatformDynamicImport} - import { AppModule } from "./app/app.module"; - - ${handleHmrOptionsDeclaration} - ${handleHmrOptionsCode} - ${acceptMainModuleCode} - - ${nsDynamicPlatformCall}(${getAppOptions("{ bootInExistingPage: true }")}).bootstrapModule(AppModule); - `, - transformedFileWithAot: ` - ${handleHmrPlatformStaticImport} - ${handleAotPlatformStaticImport} - ${handleAotNgFactoryImport} - - ${handleHmrOptionsDeclaration} - ${handleHmrOptionsAotCode} - ${acceptMainModuleAotCode} - - ${nsStaticPlatformCall}(${getAppOptions("{ bootInExistingPage: true }")}).bootstrapModuleFactory(${nsFactoryImportName}.AppModuleNgFactory); - ` - }, - { - name: "should handle HMR when platformNativeScriptDynamic is called with appOptions variable", - rawFile: ` - import { platformNativeScriptDynamic } from "nativescript-angular/platform"; - import { AppModule } from "./app/app.module"; - const appOptions = { bootInExistingPage: true }; - platformNativeScriptDynamic(appOptions).bootstrapModule(AppModule); + import { platformNativeScript } from "@nativescript/angular"; + platformNativeScript().bootstrapModule(SyntaxErrorModule); `, transformedFile: ` - ${handleHmrPlatformDynamicImport} - import { AppModule } from "./app/app.module"; - - var ${GeneratedDynamicAppOptions} = {}; - ${handleHmrOptionsCode} - ${acceptMainModuleCode} - - const appOptions = { bootInExistingPage: true }; - - ${nsDynamicPlatformCall}(${getAppOptions("appOptions")}).bootstrapModule(AppModule); + import { platformNativeScript } from "@nativescript/angular"; + platformNativeScript().bootstrapModule(SyntaxErrorModule); `, transformedFileWithAot: ` - ${handleHmrPlatformStaticImport} - ${handleAotPlatformStaticImport} - ${handleAotNgFactoryImport} - - var ${GeneratedDynamicAppOptions} = {}; - ${handleHmrOptionsAotCode} - ${acceptMainModuleAotCode} - - const appOptions = { bootInExistingPage: true }; - - ${nsStaticPlatformCall}(${getAppOptions("appOptions")}).bootstrapModuleFactory(${nsFactoryImportName}.AppModuleNgFactory); + import { platformNativeScript } from "@nativescript/angular"; + platformNativeScript().bootstrapModule(SyntaxErrorModule); ` }, - - { - name: "should handle HMR when platformNativeScriptDynamic is called with multiple arguments", - rawFile: ` - import { platformNativeScriptDynamic } from "nativescript-angular/platform"; - import { AppModule } from "./app/app.module"; - platformNativeScriptDynamic({ bootInExistingPage: true }, ["provider1", "provider2"]).bootstrapModule(AppModule); - `, - transformedFile: ` - ${handleHmrPlatformDynamicImport} - import { AppModule } from "./app/app.module"; - - ${handleHmrOptionsDeclaration} - ${handleHmrOptionsCode} - ${acceptMainModuleCode} - - ${nsDynamicPlatformCall}(${getAppOptions("{ bootInExistingPage: true }")}, ["provider1", "provider2"]).bootstrapModule(AppModule); - `, - transformedFileWithAot: ` - ${handleHmrPlatformStaticImport} - ${handleAotPlatformStaticImport} - ${handleAotNgFactoryImport} - - ${handleHmrOptionsDeclaration} - ${handleHmrOptionsAotCode} - ${acceptMainModuleAotCode} - - ${nsStaticPlatformCall}(${getAppOptions("{ bootInExistingPage: true }")}, ["provider1", "provider2"]).bootstrapModuleFactory(${nsFactoryImportName}.AppModuleNgFactory); - ` - }, - { - name: "should accept HMR before the user when custom handling is in place", - rawFile: ` - import { platformNativeScriptDynamic } from "nativescript-angular/platform"; - import { AppModule } from "./app/app.module"; - - if (module["hot"]) { - module["hot"].accept(["./app/app.module"], function () { - // customHandling - }); - } - - platformNativeScriptDynamic().bootstrapModule(AppModule); - `, - transformedFile: ` - ${handleHmrPlatformDynamicImport} - import { AppModule } from "./app/app.module"; - - ${handleHmrOptionsDeclaration} - ${handleHmrOptionsCode} - ${acceptMainModuleCode} - - if (module["hot"]) { - module["hot"].accept(["./app/app.module"], function () { - // customHandling - }); - } - - ${nsDynamicPlatformCall}(${defaultAppOptions}).bootstrapModule(AppModule); - `, - transformedFileWithAot: ` - ${handleHmrPlatformStaticImport} - ${handleAotPlatformStaticImport} - ${handleAotNgFactoryImport} - - ${handleHmrOptionsDeclaration} - ${handleHmrOptionsAotCode} - ${acceptMainModuleAotCode} - - if (module["hot"]) { - module["hot"].accept(["./app/app.module"], function () { - // customHandling - }); - } - - ${nsStaticPlatformCall}(${defaultAppOptions}).bootstrapModuleFactory(${nsFactoryImportName}.AppModuleNgFactory); - ` - } + ]; testCases.forEach((testCase: any) => { it(`${testCase.name}`, async () => { @@ -364,9 +72,8 @@ describe("@ngtools/webpack transformers", () => { }, }; - const aotTransformer = nsReplaceBootstrap(() => ngCompiler, testFile, projectDir); const hmrTransformer = nsSupportHmrNg(() => ngCompiler, testFile); - const result = transformTypescript(undefined, [aotTransformer, hmrTransformer], program, compilerHost); + const result = transformTypescript(undefined, [hmrTransformer], program, compilerHost); expect(tags.oneLine`${result}`).toEqual(tags.oneLine`${output}`); }); diff --git a/unit-testing-config-loader.js b/unit-testing-config-loader.js index e3d4a2ff..e0c362e7 100644 --- a/unit-testing-config-loader.js +++ b/unit-testing-config-loader.js @@ -17,11 +17,11 @@ module.exports = function ({ appFullPath, projectRoot, angular, rootPagesRegExp const runnerRelativePath = convertSlashesInPath(relative(appFullPath, runnerFullPath)); const appCssFilePath = convertSlashesInPath(join(runnerRelativePath, "app.css")); let source = ` - require("tns-core-modules/bundle-entry-points"); + require("@nativescript/core/bundle-entry-points"); const runnerContext = require.context("${runnerRelativePath}", true, ${rootPagesRegExp}); global.registerWebpackModules(runnerContext); global.registerModule("${appCssFilePath}", () => require("${appCssFilePath}")); - require("tns-core-modules/application").setCssFileName("${appCssFilePath}"); + require("@nativescript/core/application").setCssFileName("${appCssFilePath}"); `; if (angular) { diff --git a/verify/update.js b/verify/update.js index 1484917f..c54f84ec 100644 --- a/verify/update.js +++ b/verify/update.js @@ -9,7 +9,7 @@ const { const { forceUpdateProjectFiles } = require("../projectFilesManager"); const { forceUpdateProjectDeps } = require("../dependencyManager"); -const PLUGIN_NAME = "nativescript-dev-webpack"; +const PLUGIN_NAME = "@nativescript/webpack"; const PROJECT_DIR = getProjectDir(); function update({