I'm wanting to extend the iOS app delegate. I'm integrating with a SDK called Mobile Pay (https://github.com/MobilePayDev/MobilePay-AppSwitch-SDK/wiki/Getting-started-on-iPhone) and need to hook into the App Delegate when opening an external app for payment. For some reason the methods (such as applicationHandleOpenURL) are never called when leaving the app and opening the mobile pay app.
I've been using different examples such as nativescript-plugin-firebase and nativescript-urlhandler. Also tried https://github.com/NativeScript/sample-ios-background-execution/blob/master/app/custom-app-delegate.ts and https://docs.nativescript.org/core-concepts/application-lifecycle
The code looks like this:
private getAppDelegate() {
// Play nice with other plugins by not completely ignoring anything already added to the appdelegate
if (iosApp.delegate === undefined) {
#ObjCClass(UIApplicationDelegate)
class UIApplicationDelegateImpl extends UIResponder implements UIApplicationDelegate {
}
iosApp.delegate = UIApplicationDelegateImpl;
}
return iosApp.delegate;
}
private addDelegateMethods() {
let appDelegate = this.getAppDelegate();
console.log("er are adding this stuff to the equation lol");
appDelegate.prototype.applicationDidFinishLaunchingWithOptions = (application, launchOptions) => {
console.log("we are here or did finish?");
return true;
};
appDelegate.prototype.applicationHandleOpenURL = (application: UIApplication, url: NSURL): boolean => {
console.log("we are here or what?");
MobilePayManager.sharedInstance().handleMobilePayCallbacksWithUrlSuccessErrorCancel(
url, this.onPaymentSuccess, this.onPaymentFailure, this.onPaymentCancel);
return true;
};
appDelegate.prototype.applicationOpenURLOptions = (app: UIApplication, url: NSURL, options: NSDictionary<string, any>): boolean => {
console.log("we are here or what?");
MobilePayManager.sharedInstance().handleMobilePayCallbacksWithUrlSuccessErrorCancel(
url, this.onPaymentSuccess, this.onPaymentFailure, this.onPaymentCancel);
return true;
};
appDelegate.prototype.openURL = (url: NSURL): boolean => {
console.log("we are here or what?");
MobilePayManager.sharedInstance().handleMobilePayCallbacksWithUrlSuccessErrorCancel(
url, this.onPaymentSuccess, this.onPaymentFailure, this.onPaymentCancel);
return true;
};
appDelegate.prototype.applicationOpenURLSourceApplicationAnnotation = (application: UIApplication, url: NSURL, sourceApplication: string, annotation: any): boolean => {
console.log("we are here or what?");
MobilePayManager.sharedInstance().handleMobilePayCallbacksWithUrlSuccessErrorCancel(
url, this.onPaymentSuccess, this.onPaymentFailure, this.onPaymentCancel);
return true;
};
}
and then my package.json is here:
"dependencies": {
"#angular/animations": "~7.2.0",
"#angular/common": "~7.2.0",
"#angular/compiler": "~7.2.0",
"#angular/core": "~7.2.0",
"#angular/forms": "~7.2.0",
"#angular/http": "~7.2.0",
"#angular/platform-browser": "~7.2.0",
"#angular/platform-browser-dynamic": "~7.2.0",
"#angular/router": "~7.2.0",
"nativescript-angular": "~7.2.0",
"nativescript-mobilepay": "1.0.5",
"nativescript-theme-core": "~1.0.4",
"reflect-metadata": "~0.1.12",
"rxjs": "~6.3.0",
"tns-core-modules": "~5.3.0",
"zone.js": "~0.8.26"
},
"devDependencies": {
"#angular/compiler-cli": "~7.2.0",
"#nativescript/schematics": "~0.5.0",
"#ngtools/webpack": "~7.2.0",
"nativescript-dev-typescript": "~0.9.0",
"nativescript-dev-webpack": "~0.21.0"
},
Expecting in method to be called applicationHandleOpenURL.
If you are assigning the delegate in your component's ngOnInit, then that's the issue here.
You are suppose to do it in main.ts before platformNativeScriptDynamic(...).bootstrapModule(...). By the time ngOnInit is executed, the default app delegate would have been already created.
Related
I'm trying to run npm run development, but I got a typescript error here
let { Chunks } = require('../Chunks');
let File = require('../File');
let VueVersion = require('../VueVersion');
let AppendVueStylesPlugin = require('../webpackPlugins/Css/AppendVueStylesPlugin');
/** #typedef {import("vue").VueLoaderOptions} VueLoaderOptions */
class Vue {
/**
* Create a new component instance.
*/
constructor() {
this.chunks = Chunks.instance();
}
/**
* Register the component.
*
* #param {object} options
* #param {number} [options.version] Which version of Vue to support. Detected automatically if not given.
* #param {string|null} [options.globalStyles] A file to include w/ every vue style block.
* #param {boolean|string} [options.extractStyles] Whether or not to extract vue styles. If given a string the name of the file to extract to.
* #param {VueLoaderOptions} [options.options] Options to pass to Vue Loader
*/
register(options = {}) {
if (
arguments.length === 2 &&
typeof arguments[0] === 'string' &&
typeof arguments[1] === 'string'
) {
throw new Error(
'mix.vue() is a feature flag. Use mix.js(source, destination).vue() instead'
);
}
this.version = VueVersion.detect(options.version);
this.options = Object.assign(
{
options: null,
globalStyles: null,
extractStyles: false
},
options
);
Mix.globalStyles = this.options.globalStyles;
Mix.extractingStyles = !!this.options.extractStyles;
}
/**
* Required dependencies for the component.
*/
dependencies() {
this.requiresReload = true;
let dependencies = [
this.version === 2 ? 'vue-template-compiler' : '#vue/compiler-sfc',
this.version === 2 ? 'vue-loader#^15.9.5' : 'vue-loader#^16.1.0'
];
if (this.options.extractStyles && this.options.globalStyles) {
dependencies.push('sass-resources-loader');
}
return dependencies;
}
/**
* Override the generated webpack configuration.
*
* #param {Object} webpackConfig
*/
webpackConfig(webpackConfig) {
// push -> unshift to combat vue loader webpack 5 bug
webpackConfig.module.rules.unshift({
test: /\.vue$/,
use: [
{
loader: this._mix.resolve('vue-loader'),
options: this.options.options || Config.vue || {}
}
]
});
// Alias Vue to its ESM build if the user has not already given an alias
webpackConfig.resolve.alias = webpackConfig.resolve.alias || {};
if (!webpackConfig.resolve.alias['vue$']) {
webpackConfig.resolve.alias['vue$'] = this.aliasPath();
}
webpackConfig.resolve.extensions.push('.vue');
this.updateChunks();
}
aliasPath() {
if (this.version === 2) {
return this.options.runtimeOnly
? 'vue/dist/vue.runtime.esm.js'
: 'vue/dist/vue.esm.js';
}
return this.options.runtimeOnly
? 'vue/dist/vue.runtime.esm-bundler.js'
: 'vue/dist/vue.esm-bundler.js';
}
/**
* webpack plugins to be appended to the master config.
*/
webpackPlugins() {
let { VueLoaderPlugin } = require(this._mix.resolve('vue-loader'));
return [new VueLoaderPlugin(), new AppendVueStylesPlugin()];
}
/**a
* Update CSS chunks to extract vue styles
*/
updateChunks() {
if (this.options.extractStyles === false) {
return;
}
this.chunks.add(
'styles-vue',
this.styleChunkName(),
[/.vue$/, module => module.type === 'css/mini-extract'],
{
chunks: 'all',
enforce: true,
type: 'css/mini-extract'
}
);
}
/**
* Get the name of the style chunk.
*
* #returns {string}
*/
styleChunkName() {
// If the user set extractStyles: true, we'll try
// to append the Vue styles to an existing CSS chunk.
if (this.options.extractStyles === true) {
let chunk = this.chunks.find((chunk, id) => id.startsWith('styles-'));
if (chunk) {
return chunk.name;
}
}
return this.extractFile().relativePathWithoutExtension();
}
/**
* Get a new File instance for the extracted file.
*
* #returns {File}
*/
extractFile() {
return new File(this.extractFileName());
}
/**
* Determine the extract file name.
*
* #return {string}
*/
extractFileName() {
let fileName =
typeof this.options.extractStyles === 'string'
? this.options.extractStyles
: '/css/vue-styles.css';
return fileName.replace(Config.publicPath, '').replace(/^\//, '');
}
}
module.exports = Vue;
**package.json
{
"private": true,
"scripts": {
"development": "mix",
"hot": "mix watch --hot",
"production": "mix --production",
"watch": "mix watch",
"watch-poll": "mix watch -- --watch-options-poll=1000"
},
"dependencies": {
"#chenfengyuan/vue-countdown": "^1.1.5",
"#mdi/light-font": "^0.2.63",
"#types/ziggy-js": "^0.9.0",
"#vue/cli-service": "^5.0.4",
"axios": "^0.21.1",
"dotenv": "^16.0.0",
"eslint": "^7.18.0",
"laravel-echo": "^1.10.0",
"lottie-player-vue": "0.0.16",
"object-to-formdata": "^4.1.0",
"pusher-js": "^7.0.2",
"qrcode": "^1.5.0",
"read-excel-file": "^5.2.28",
"sweetalert2": "^9.17.2",
"v-money": "^0.8.1",
"vee-validate": "^2.2.15",
"vform": "^1.0.1",
"vue-axios": "^2.1.5",
"vue-cli": "^2.9.6",
"vue-countdown": "^1.0.4",
"vue-excel-xlsx": "^1.2.2",
"vue-moment": "^4.1.0",
"vue-qrcode-component": "^2.1.1",
"vue-resource": "^1.5.3",
"vue-sessionstorage": "^1.0.0",
"vue-social-auth": "^1.4.9",
"vue-socket.io": "^3.0.10",
"vue2-storage": "^5.0.0",
"vuedraggable": "^2.24.3",
"vuetify": "^2.6.0",
"vuex": "^3.6.2",
"vuex-map-fields": "^1.4.1",
"ziggy": "^2.4.0",
"ziggy-js": "^1.4.3"
},
"devDependencies": {
"#fortawesome/fontawesome-free": "^5.12.0",
"#inertiajs/inertia": "^0.11.0",
"#inertiajs/inertia-vue": "^0.8.0",
"#inertiajs/progress": "^0.2.7",
"#mdi/font": "^4.9.95",
"#mdi/js": "^5.9.55",
"#nuxtjs/vuetify": "^1.12.3",
"#popperjs/core": "^2.10.2",
"bootstrap": "^5.1.3",
"browser-sync": "^2.26.13",
"browser-sync-webpack-plugin": "^2.3.0",
"cross-env": "^7.0.3",
"deepmerge": "^4.2.2",
"eslint-plugin-import": "^2.19.1",
"eslint-plugin-vue": "^7.5.0",
"font-awesome": "^4.7.0",
"laravel-mix": "6.0.6",
"lodash": "^4.17.20",
"material-design-icons-iconfont": "^6.4.1",
"resolve-url-loader": "^3.1.2",
"roboto-fontface": "^0.10.0",
"sass": "~1.32",
"sass-loader": "^11.1.1",
"vue": "^2.6.12",
"vue-cli-plugin-vuetify": "~2.5.8",
"vue-loader": "^14.2.4",
"vue-template-compiler": "^2.7.14",
"vuetify": "^2.4.2",
"vuetify-loader": "^1.7.0",
"webpack": "^5.75.0",
"webpack-cli": "^5.0.1"
}
}
**
I dont know why I got this error.
I'm new to Vue.js, can someone enlighten me to how to use and continue other's project from scratch ? I got a lot of problems, such as the Vue code not showing changes in the application in my localhost.
I have a problem with #nestjs/graphql with serverless.
When i start the app normaly with the $ nest start command, it's working well without any error.
But with the $ sls offline command, it's not running and i have this error when i go to the /graphql (playground) endpoint :
offline: ANY /graphql (λ: graphql)
[Nest] 49532 - 04/02/2022, 22:56:30 LOG [NestFactory] Starting Nest application...
[Nest] 49532 - 04/02/2022, 22:56:30 LOG [InstanceLoader] ConfigHostModule dependencies initialized +35ms
[Nest] 49532 - 04/02/2022, 22:56:30 LOG [InstanceLoader] ConfigModule dependencies initialized +1ms
[Nest] 49532 - 04/02/2022, 22:56:30 LOG [InstanceLoader] JwtModule dependencies initialized +1ms
[Nest] 49532 - 04/02/2022, 22:56:30 LOG [InstanceLoader] GraphQLModule dependencies initialized +0ms
[Nest] 49532 - 04/02/2022, 22:56:30 LOG [InstanceLoader] GraphQLSchemaBuilderModule dependencies initialized +0ms
[Nest] 49532 - 04/02/2022, 22:56:30 LOG [InstanceLoader] GraphQLModule dependencies initialized +1ms
[Nest] 49532 - 04/02/2022, 22:56:30 LOG [InstanceLoader] DatabaseModule dependencies initialized +166ms
[Nest] 49532 - 04/02/2022, 22:56:30 LOG [InstanceLoader] AuthModule dependencies initialized +2ms
[Nest] 49532 - 04/02/2022, 22:56:30 LOG [InstanceLoader] UsersModule dependencies initialized +1ms
offline: Failure: Cannot determine a GraphQL output type for the "roles". Make sure your class is decorated with an appropriate decorator.
I think the problem is located on a specific objectType who expose the User (an other objectType+Entity).
// auth.models.ts
import { User } from '#features/graphql/users/entities';
import { Field, ObjectType } from '#nestjs/graphql';
#ObjectType()
export class SignInUserModel {
#Field(() => User, { nullable: true })
user?: User;
#Field(() => String, { nullable: true })
accessToken?: string;
#Field(() => String, { nullable: true })
refreshToken?: string;
}
Because if i remove the User field from the SignInUserModel, the problem disappear ... someone have an idea of what i need to do ?
A specific decorator or something is missing for roles in my User model ?
I am totally lost haha
About my code:
// lambda.handler
import { defaultConfig } from '#config';
import { GraphQLModule } from '#features/graphql/graphql.module';
import { Logger, ValidationPipe } from '#nestjs/common';
import { NestFactory } from '#nestjs/core';
import serverlessExpress from '#vendia/serverless-express';
import { Callback, Context, Handler } from 'aws-lambda';
let server: Handler;
async function bootstrap() {
const config = defaultConfig();
const app = await NestFactory.create(GraphQLModule);
// Logger
if (config.isLoggerEnabled) app.useLogger(app.get(Logger));
// Validation
app.useGlobalPipes(new ValidationPipe());
await app.init();
const expressApp = app.getHttpAdapter().getInstance();
return serverlessExpress({ app: expressApp });
}
export const handler: Handler = async (
event: any,
context: Context,
callback: Callback,
) => {
server = server ? server : await bootstrap();
return server(event, context, callback);
};
// graphql.module.ts
import { ConfigModule, graphqlConfig } from '#config';
import { AppService } from '#features/app.service';
import { UsersModule } from '#features/graphql/users/users.module';
import { AuthModule } from '#features/_auth/auth.module';
import { Module } from '#nestjs/common';
import { GraphQLModule as NESTJSGraphQLModule } from '#nestjs/graphql';
#Module({
imports: [
ConfigModule,
AuthModule,
NESTJSGraphQLModule.forRoot({
installSubscriptionHandlers: true,
autoSchemaFile: graphqlConfig().generatedSchemaFileLocation,
sortSchema: true,
debug: graphqlConfig().isDebugEnabled,
introspection: true,
context: ({ req }) => ({ headers: req.headers }),
playground: graphqlConfig().isPlaygroundEnabled
? {
settings: { 'schema.polling.enable': false },
}
: false,
}),
UsersModule,
],
providers: [AppService],
})
export class GraphQLModule {
constructor(private readonly appService: AppService) {
if (!this.appService.checkEnv()) process.exit();
}
}
// user.entity.ts
import { UserRole } from '#features/graphql/users/users.enums';
import { Field, ObjectType } from '#nestjs/graphql';
import { Column, Entity, PrimaryGeneratedColumn } from 'typeorm';
#ObjectType()
#Entity({ name: 'users' })
export class User {
#PrimaryGeneratedColumn('uuid')
#Field(() => String)
id: string;
#Column('text')
#Field(() => String)
firstName: string;
#Column('text')
#Field(() => String)
lastName: string;
#Column('text')
#Field(() => String)
email: string;
#Column({ type: 'enum', enum: UserRole, array: true, default: ['USER'] })
#Field(() => [UserRole])
roles: UserRole[];
...
}
// user.enums.ts
export enum UserRole {
ADMIN = 'ADMIN',
MODERATOR = 'MODERATOR',
USER = 'USER',
}
// serverless.ts
import type { AWS } from '#serverless/typescript';
import { config as dotEnvConfig } from 'dotenv';
import * as envVar from 'env-var';
import packageConfig from './package.json';
dotEnvConfig();
const serverlessConfiguration: AWS = {
service: packageConfig.name,
useDotenv: true,
frameworkVersion: '*',
plugins: {
modules: [
'serverless-plugin-optimize',
'serverless-offline',
'serverless-plugin-warmup',
],
},
custom: {
warmup: {
default: {
enabled: true,
},
},
'serverless-offline': {
noPrependStageInUrl: true,
},
},
provider: {
name: 'aws',
lambdaHashingVersion: '20201221',
runtime: 'nodejs12.x',
apiGateway: {
shouldStartNameWithService: true,
},
environment: {
/* ... my envs ... */
},
},
functions: {
graphql: {
handler: 'dist/src/features/graphql/_lambda.handler',
events: [
{
http: {
method: 'ANY',
path: '/graphql',
},
},
],
},
},
};
module.exports = serverlessConfiguration;
I am using packages :
"dependencies": {
"#nestjs/common": "^8.0.0",
"#nestjs/config": "^1.1.6",
"#nestjs/core": "^8.0.0",
"#nestjs/graphql": "^9.1.2",
"#nestjs/jwt": "^8.0.0",
"#nestjs/passport": "^8.1.0",
"#nestjs/platform-express": "^8.0.0",
"#nestjs/typeorm": "^8.0.3",
"#vendia/serverless-express": "^4.5.3",
"apollo-server-express": "^3.6.2",
"aws-lambda": "^1.0.7",
"bcryptjs": "^2.4.3",
"class-validator": "^0.13.2",
"env-var": "^7.1.1",
"graphql": "^15",
"nestjs-pino": "^2.5.0",
"passport": "^0.5.2",
"passport-local": "^1.0.0",
"pg": "^8.7.1",
"pino-http": "^6.6.0",
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"rxjs": "^7.2.0",
"typeorm": "^0.2.41"
},
"devDependencies": {
"#faker-js/faker": "^6.0.0-alpha.5",
"#nestjs/cli": "^8.0.0",
"#nestjs/schematics": "^8.0.0",
"#nestjs/testing": "^8.0.0",
"#serverless/typescript": "^3.0.0",
"#types/aws-lambda": "^8.10.92",
"#types/bcryptjs": "^2.4.2",
"#types/express": "^4.17.13",
"#types/jest": "27.0.2",
"#types/node": "^16.0.0",
"#types/passport-local": "^1.0.34",
"#types/supertest": "^2.0.11",
"#typescript-eslint/eslint-plugin": "^5.0.0",
"#typescript-eslint/parser": "^5.0.0",
"eslint": "^8.0.1",
"eslint-config-prettier": "^8.3.0",
"eslint-plugin-prettier": "^4.0.0",
"jest": "^27.2.5",
"npm-run-all": "^4.1.5",
"prettier": "^2.3.2",
"serverless-offline": "^8.4.0",
"serverless-plugin-optimize": "^4.2.1-rc.1",
"serverless-plugin-warmup": "^6.2.0",
"source-map-support": "^0.5.20",
"supertest": "^6.2.2",
"ts-jest": "^27.1.3",
"ts-loader": "^9.2.3",
"ts-node": "^10.0.0",
"tsc-alias": "^1.5.0",
"tsconfig-paths": "^3.12.0",
"typescript": "^4.3.5"
}
Thanks for your help and I hope you have a solution :)
According to this page https://docs.nestjs.com/graphql/unions-and-enums
enums need to be declared with the function registerEnumType
registerEnumType(UserRole, {
name: 'UserRole',
});
I have added jasmine-marbles to my project and I am getting error messages like this:
Expected $[0].frame = 20 to equal 70.
Expected $[0].notification.kind = 'E' to equal 'N'.
Expected $[0].notification.value = undefined to equal LoadSuccess().
instead of something like this:
Expected
{"frame":50,"notification":{"kind":"N","value":{"payload":"[
...
to deep equal
{"frame":40,"notification":{"kind":"N","value":{"payload":"[
...
Test:
it('should loadData$', () => {
const action = new LoadRequest('123');
const completion = new LoadSuccess({});
actions$.stream = hot('-a', { a: action });
const response = cold('-a|', { a: {} });
const expected = cold('---c', { c: completion });
client.loadData = () => response;
expect(effects.loadData$).toBeObservable(expected);
});
package.json:
"devDependencies": {
"jasmine-core": "^2.3.4",
"jasmine-marbles": "^0.2.0",
"jasmine-spec-reporter": "^3.2.0",
"karma": "1.4.1",
"karma-chrome-launcher": "^2.0.0",
"karma-coverage": "^1.0.0",
"karma-jasmine": "^1.1.0",
"karma-mocha-reporter": "^2.2.5",
"karma-remap-istanbul": "0.2.1",
"karma-sourcemap-loader": "^0.3.7",
"karma-webpack": "2.0.2",
...
How to fix the test failure message? Is it related to some karma reporter / plugin / missing library?
See package.json,
"jasmine": "^2.5.3",
"jasmine-core": "~2.5.2",
I don't know if it makes a difference.
Angular HttpClient doesnt send data to controller.
I get a error 500 (because username in controller is null) when i try to execute fun().
test.sevice.ts
import { Injectable } from '#angular/core';
import {HttpClient} from "#angular/common/http";
import 'rxjs/Rx';
import { Observable } from 'rxjs/Rx';
#Injectable()
export class RestService {
private EndPointUrl = 'http://127.0.0.1:8080/api/test';
constructor(public http: HttpClient){}
fun(){
this.test().subscribe((data)=>console.log(data));
}
test(): Observable<string>{
let params = new URLSearchParams();
params.append("grant_type",'password');
params.append('username', 'Name');
let body = params.toString();
let headers = new HttpHeaders();
headers.set('Content-Type', 'application/x-www-form-urlencoded');
return this.http.post<string>(this.EndPointUrl, body);
}
}
package.json
...
"dependencies": {
"#angular/common": "4.3.4",
"#angular/compiler": "4.3.4",
"#angular/compiler-cli": "4.3.4",
"#angular/core": "4.3.4",
"#angular/forms": "4.3.4",
"#angular/http": "4.3.4",
"#angular/common/http": "4.3.4",
"#angular/platform-browser": "4.3.4",
"#angular/platform-browser-dynamic": "4.3.4",
...},
Spring MVC Controller:
#RequestMapping(value="/test",
method = RequestMethod.POST,
produces=MediaType.APPLICATION_JSON_VALUE)
public String[] test(HttpServletRequest request){
Map<String, String[]> parameters = request.getParameterMap();
return parameters.get("username");
}
Request from postMan works, and returns some username.
Does anyone know what I'm doing wrong?
What i can see is you're using HttpClient not correctly ... cause it came in angular 4.3.* and is little bit different from the old Http ..
you don't have to do anymore .json() ..so for example:
return this.http.post<string>(this.EndPointUrl, body) //<-- IT DON'T NEED HEADERS F.. ITKNOWS IT'S A application/x-www-form-urlencoded
.map((resp) => {
return resp; //<-- HERE resp is your resp.json()
})
.catch((err)=>{
console.log(err);
}); }
and then your post:
let dataForm = new URLSearchParams();
dataForm.append('userName', "MyUserName");
let body = dataForm.toString();
return this.http.post<string>(this.EndPointUrl, body) //<-- IT DON'T NEED HEADERS F.. ITKNOWS IT'S A application/x-www-form-urlencoded
.map((resp) => {
return resp; //<-- HERE resp is your resp.json()
})
.catch((err)=>{
console.log(err);
}); }
use Http instead of HttpClient:
import {Http} from '#angular/http';
...
constructor(private http: Http) { }
...
I have been searching for answer an all weekend. To no avail. I have been down the webpack rabbit hole with elixir 6 and back to browserify.
This gist here looked promising: https://gist.github.com/sagalbot/6150d4f536af7b4c4f9a9879856e595d
// Default babel presets are ['es2015', 'react']
// https://babeljs.io/docs/plugins/preset-stage-2/
elixir.config.js.babel.options.presets = ['es2015', 'stage-2'];
However elixir.config.js.babel is undefined — why is that? Was there a refactor done? I can't get it working.
All I want to do is enable stage-2. (https://babeljs.io/docs/plugins/preset-stage-2/)
My gulp file
require("laravel-elixir-remove");
require("laravel-elixir-bless");
require("laravel-elixir-browserify-official");
//require('laravel-elixir-scss-lint'); // this doesn't work under elixir ^6.0.0-10
require('elixir-typescript');
require("./gulp/ts.lint");
var elixir = require("laravel-elixir");
var jsonminify = require("jsonminify");
var config = require("./gulp/parse.config");
var argv = require("yargs").argv;
var fs = require("fs");
elixir.config.js.babel.enabled = true;
// grab the JSON file and make a copy of it.
// strip out the comments from the JSON file using jsonminify
var ORIGINAL_CONFIG = config.getJSON("./build.config.json");
//set the replacement section of the JSON file to modify the remainder of the JSON
config.setConfigKey("replacements");
config.parse(ORIGINAL_CONFIG);
elixir = config.setElixirPaths(elixir);
/*======================================================================================*/
// BROWSERIFY OPERATIONS
/*======================================================================================*/
var BROWSERIFYCONFIG = elixir.config.js.browserify;
BROWSERIFYCONFIG.plugins.push({
name: "tsify", options: {
target: "es5",
experimentalDecorators: true,
babelify: {
extensions: [".tsx", ".ts"]
}
}
});
// can't get this working, I can't enable the spread/rest operator.
// elixir.config.js.browserify.transformers
// .find(transformer => transformer.name === 'babelify')
// .options.plugins = [
// 'syntax-object-rest-spread',
// 'transform-object-rest-spread'
// ];
BROWSERIFYCONFIG.plugins.push(
{
name: "factor-bundle",
options: {
// generate js files from the input, the order is crucial
outputs: config.get("browserify.in", "js")
}
}
);
// this is undefined. When was the babel property removed from the elixir config object?!!
//console.log(elixir.config.js.babel);
//elixir.config.js.babel.options.presets = ['es2015', 'stage-2'];
/*======================================================================================*/
// BUILD
/*======================================================================================*/
elixir(build);
function build(mix) {
if (!argv.hasOwnProperty("scss")) {
// if there is no public dir, create it, as browserify expects
if (!fs.existsSync(config.get("replacements.outPath"))) {
fs.mkdirSync(config.get("replacements.outPath"));
fs.mkdirSync(config.get("replacements.js"));
}
// browserify node_modules and write out
mix.browserify(
// factor all the files in order:
config.get("browserify.in", "ts"),
// and generate one file that is common to all of them:
config.get("browserify.out", "js")
);
}
//
// if (!argv.hasOwnProperty("js")) {
//
// // concatenate js files first
mix.scripts(
config.get("concat.in", "js"),
config.get("concat.out", "js")
);
//
// //generate the css ( note we can't loop over )
// mix.sass(config.get('scss.0.in', 'scss'), config.get('scss.0.out', 'css'),{sourceComments:true})
// .sass(config.get('scss.1.in', 'scss'), config.get('scss.1.out', 'css'))
// .sass(config.get('scss.2.in', 'scss'), config.get('sass.2.out', 'css'))
// .sass(config.get('scss.3.in', 'scss'), config.get('scss.3.out', 'css'))
// .browserSync({
// files: ["**/*.css", "**/*.js", "**/*.php"],
// proxy: "website.mock",
// port: 4000,
// logPrefix: "Laravel Eixir BrowserSync"
// });
//
// if(!argv.hasOwnProperty("production")){
// mix.scssLint(config.get('sasslint.in', 'scss'));
// mix.tslint(config.get("tslint.in", "ts"), config.getJSON(config.get("tslint.rules", "json")));
// }
//
// // copy debug files over — temporary
// mix.copy(config.get('copy.0.in', 'css'), config.get('copy.0.out', 'css'))
// .copy(config.get('copy.1.in', 'css'), config.get('copy.1.out', 'css'))
// .copy(config.get('copy.2.in', 'js'), config.get('copy.2.out', 'js'))
// .copy(config.get('copy.3.in'), config.get('copy.3.out'))
// .bless(config.get('bless.0.in', 'css'), {imports: true});
// }
}
I have a .babelrc file
{
"presets": ["stage-2"],
"comments": true
}
Which seems to be ignored.
Package.json
{
"devDependencies": {
"alterclass": "git+https://github.com/sidouglas/alter-class#1.0",
"babel": "^6.5.2",
"babel-core": "^6.10.4",
"babel-preset-stage-2": "^6.13.0",
"babel-register": "^6.9.0",
"bootstrap-pull": "git+https://github.com/sidouglas/bootstrap-pull.git#3.0.2",
"browserify-shim": "^3.8.12",
"dot-object": "^1.4.1",
"elixir-jasmine": "0.0.4",
"gulp": "^3.9.1",
"gulp-replace-task": "^0.11.0",
"gulp-tslint": "^6.0.1",
"jasmine-fixture": "^2.0.0",
"jasmine-jquery": "^2.1.1",
"jsonminify": "^0.4.1",
"karma": "^1.1.1",
"karma-chrome-launcher": "^1.0.1",
"karma-firefox-launcher": "^1.0.0",
"karma-ios-simulator-launcher": "0.0.4",
"karma-jasmine": "^1.0.2",
"karma-safari-launcher": "^1.0.0",
"laravel-elixir": "^6.0.0-10",
"laravel-elixir-bless": "^2.0.0",
"laravel-elixir-browserify-official": "^0.1.3",
"laravel-elixir-browsersync": "^0.1.5",
"laravel-elixir-browsersync-official": "^1.0.0",
"laravel-elixir-remove": "^0.2.1",
"lodash": "^4.13.1",
"node-sass": "^3.8.0",
"retyped-bowser-tsd-ambient": "0.0.0-0",
"run-sequence": "^1.2.1",
"sass-convert": "^0.5.2",
"supplant": "^0.2.0",
"tsify": "^1.0.4",
"tslint": "^3.13.0",
"typescript": "^1.9.0-dev.20160605-1.0",
"yargs": "^4.8.0"
},
"dependencies": {
"babel-plugin-transform-object-rest-spread": "^6.8.0",
"babel-preset-es2015": "^6.14.0",
"babel-preset-react": "^6.11.1",
"boilerplate": "^0.5.0",
"bootstrap": "^3.3.6",
"bootstrap-sass": "^3.3.6",
"bootstrap-select": "^1.10.0",
"bowser": "^1.4.2",
"del": "^2.2.0",
"elixir-typescript": "^2.0.0",
"factor-bundle": "^2.5.0",
"gulp-change": "^1.0.0",
"gulp-shell": "^0.5.2",
"include-media": "^1.4.5",
"jquery": "^2.2.4",
"jquery-replace-class": "0.0.1",
"lodash": "^4.14.0",
"material-kit": "git://github.com/tfsimondouglas/material-kit-bootstrap-3.git#1.1",
"nouislider": "^8.5.1",
"partition-bundle": "^2.5.0",
"redux": "^3.5.2",
"requirejs": "^2.2.0",
"riot": "^2.5.0",
"riot-ts": "git://github.com/tfsimondouglas/riot-ts.git",
"tf-modernizr": "git://github.com/tomorrowfinance/tf-modernizr.git",
"webshim": "^1.15.10",
"wnumb": "git://github.com/tannerhodges/wnumb"
},
"scripts": {
"test": "protractor protractor.conf.js",
"postinstall": "node node_modules/.bin/gulp --production",
"watch": "node node_modules/.bin/gulp watch",
"gulp": "node node_modules/.bin/gulp",
"kill": "for pid in `ps -ef | grep gulp | awk '{print $2}'` ; do kill -9 $pid ; done",
"start": "npm run watch",
"restart": "npm run kill & npm start",
"build": "node node_modules/.bin/gulp --production"
}
}
Edit 29-08-2016
So a simple test:
let { x, y, ...z } = { x: 1, y: 2, a: 3, b: 4 };
console.log(x); // 1
console.log(y); // 2
console.log(z); // { a: 3, b: 4 }
// Spread properties
let n = { x, y, ...z };
console.log(n); // { x: 1, y: 2, a: 3, b: 4 }
Causes this error:
[14:39:26] Starting 'all'...
[14:39:26] Starting 'browserify'...
{ [TypeScript error: ...path ommitted...app.ts(3,13): Error TS1180: Property destructuring pattern expected.]
message: '...path ommitted...app.ts(3,13): Error TS1180: Property destructuring pattern expected.',
fileName: '...path ommitted...app.ts',
line: 3,
column: 13,
name: 'TypeScript error' }
{ [TypeScript error: ...path ommitted...app.ts(9,17): Error TS1136: Property assignment expected.]
message: '...path ommitted...app.ts(9,17): Error TS1136: Property assignment expected.',
fileName: '...path ommitted...app.ts',
line: 9,
column: 17,
name: 'TypeScript error' }
[14:39:27] Finished 'browserify' after 547 ms
This one helped me with similar issue:
Original (c) #michael-hsu https://stackoverflow.com/a/38194213/741782
You should override exactly babelify transformer:
elixir.config.js.browserify.transformers
.find(transformer => transformer.name === 'babelify')
.options = {
presets: ['es2015', 'react', 'stage-0', 'stage-1', 'stage-2'],
plugins: ['transform-class-properties'],
};