Testing babel-preset-env using package.json - babel-preset-env

Noob question here. Trying to assure myself that babel-preset-env works.
I install babel-core and babel-preset-env:
yarn add --dev babel-core
yarn add --dev babel-preset-env
My package.json has:
"babel": {
"presets": [
[
"env",
{
"targets": {
"browsers": [
"IE >= 8"
]
}
}
]
]
},
I create a JS script to test:
fs.readFile('my.js', 'utf8', (err, data) => {
if (err) throw err;
let babel = require("babel-core");
let result = babel.transform(data).code;
});
I test with arrow functions in my.js:
new Promise((resolve, reject) => {
console.log('whatever');
});
No matter how I tweak targets.browsers, the arrow function does not get converted.

Tested this with babel-cli. Works.
It's clear that babel-core (the Javascript API of Babel) does not pick up anything from package.json.
Filed an issue here too: https://github.com/babel/babel/issues/7647
The JS API docs probably needs to be updated.
In order to use babel-preset-env in JS API:
const { execFile } = require('child_process');
const ug = require('uglify-es');
const { execFile } = require('child_process');
execFile('npx', ['babel', 'my.js'], (err, data, stderr) => {
if (err) throw err; // U get the idea
let result = ug.minify(data, { mangle: { toplevel: true } }).code;
});

Related

How to configure cypress-sql-server with no cypress.json? (updated)

I'm trying to setup cypress-sql-server, but I'm using version 10.8.0, which does not use cypress.json to configure the environment. All of the setup instructions I've found refer to using cypress.json to configure the plug-in. With the help of u/Fody, I'm closer, but I'm still running into an error:
tasksqlServer:execute, SELECT 'Bob'
CypressError
cy.task('sqlServer:execute') failed with the following error:
The 'task' event has not been registered in the setupNodeEvents method. You must register it before using cy.task()
Fix this in your setupNodeEvents method here:
D:\git\mcare.automation\client\cypress\cypress.config.jsLearn more
node_modules/cypress-sql-server/src/commands/db.js:7:1
5 | }
6 |
> 7 | cy.task('sqlServer:execute', query).then(response => {
| ^
8 | let result = [];
9 |
cypress.config.js
const { defineConfig } = require("cypress");
const sqlServer = require("cypress-sql-server");
module.exports = defineConfig({
e2e: {
setupNodeEvents(on, config) {
// allows db data to be accessed in tests
config.db = {
"userName": "user",
"password": "pass",
"server": "myserver",
"options": {
"database": "mydb",
"encrypt": true,
"rowCollectionOnRequestCompletion": true
}
}
// code from /plugins/index.js
const tasks = sqlServer.loadDBPlugin(config.db);
on('task', tasks);
return config
// implement node event listeners here
},
},
});
testSQL.spec.js
describe('Testing SQL queries', () => {
it("It should return Bob", () => {
cy.sqlServer("SELECT 'Bob'").should('eq', 'Bob');
});
})
My versions:
\cypress> npx cypress --version
Cypress package version: 10.8.0
Cypress binary version: 10.8.0
Electron version: 19.0.8
Bundled Node version:
16.14.2
Suggestions? Is there any more info I can provide to help?
This is the install instruction currently given by cypress-sql-server for Cypress v9
Plugin file
The plug-in can be initialised in your cypress/plugins/index.js file as below.
const sqlServer = require('cypress-sql-server');
module.exports = (on, config) => {
tasks = sqlServer.loadDBPlugin(config.db);
on('task', tasks);
}
Translating that into Cypress v10+
const { defineConfig } = require('cypress')
const sqlServer = require('cypress-sql-server');
module.exports = defineConfig({
e2e: {
setupNodeEvents(on, config) {
// allows db data to be accessed in tests
config.db = {
"userName": "user",
"password": "pass",
"server": "myserver",
"options": {
"database": "mydb",
"encrypt": true,
"rowCollectionOnRequestCompletion": true
}
}
// code from /plugins/index.js
const tasks = sqlServer.loadDBPlugin(config.db);
on('task', tasks);
return config
},
},
})
Other variations work, such as putting the "db": {...} section below the "e2e: {...}" section, but not in the "env": {...} section.
Custom commands
Instructions for Cypress v9
Commands file
The extension provides multiple sets of commands. You can import the ones you need.
Example support/index.js file.
import sqlServer from 'cypress-sql-server';
sqlServer.loadDBCommands();
For Cypress v10+
Just move this code to support/e2e.js
cypress.json is a way to specify Cypress environment variables. Instead of using a cypress.json file, you can use any of the strategies in that link.
If you just wanted to include them in your cypress.config.js, it would look something like this:
const { defineConfig } = require('cypress')
module.exports = defineConfig({
e2e: {
baseUrl: 'http://localhost:1234',
env: {
db: {
// your db values here
}
}
}
})

Sqlite3 does not work after packaged in Electron application

{
"name": "ele-sqlite",
"productName": "CUSTOMER MANAGER",
"version": "1.0.0",
"description": "electron app with sqlite",
"main": "main.js",
"scripts": {
"start": "electron .",
"rebuild": "electron-rebuild -f -w sqlite3",
"postinstall": "electron-builder install-app-deps",
"build-win32": "electron-packager . customer manager --platform=win32 --icon=assets/icon.ico --prune=true --out ./dist --overwrite"
},
"devDependencies": {
"electron": "^12.0.0",
"electron-builder": "^22.10.5",
"electron-packager": "^15.2.0"
},
"dependencies": {
"electron-rebuild": "^2.3.5",
"knex": "^0.95.1",
"node-pre-gyp": "^0.11.0",
"sqlite3": "^5.0.2"
}
}
I am new to programming in general. I am trying to create a simple Electron app to store client details. Everything work very well in development and when I pack the application with electron-packager. I am
not able to store anything in the database. I have googled and apply many of the solutions but it without luck.
package.json below
const { app, BrowserWindow, ipcMain, Menu } = require('electron');
const { rebuild } = require('electron-rebuild');
// Set Env
process.env.NODE_ENV = 'production';
let mainWindow;
app.on("ready", () => {
mainWindow = new BrowserWindow({
width: 1400,
height: 900,
title:"All In One",
center: true,
show: false,
webPreferences: {
nodeIntegration: true,
contextIsolation: false
}
});
mainWindow.webContents.openDevTools()
mainWindow.loadURL(`file://${__dirname}/index.html`)
mainWindow.once("ready-to-show", () => {mainWindow.show()})
// Build menu from template
const mainMenu = Menu.buildFromTemplate(mainMenuTemplate);
// insert menu
Menu.setApplicationMenu(mainMenu);
//Info from database
const {add, listAll, findByName, update, remove} = require('./models/dbHelpers.js')
ipcMain.on("mainWindowLoaded", () => {
let resultList = listAll()
resultList.then(function(customerList){
mainWindow.webContents.send("list:customers", customerList)
});
});
// Recieve data to add customer
ipcMain.on('add:customer', (event, data) =>{
add(data)
console.log(data);
event.sender.send('add:customer', ' Customer Created!!!')
})
// Recieve data to delete customer
ipcMain.on('delete:customer', (event, id) =>{
//console.log(id)
remove(id);
event.sender.send('deleted:customer-database', 'Customer Deleted!!')
})
// Update customer
ipcMain.on('edit:customer', (event, id, data) =>{
console.log(id, data)
update(id, data);
event.sender.send('Update:customer-database', ' Customer Updated!')
})
}); // App ready & create window
const mainMenuTemplate = [
{
label: 'File',
submenu: [
{
label: 'Quit',
click(){
app.quit();
}
}
]
}
]
app.on("window-all-closed", () => {app.quit()})

Gulp and Critical CSS - TypeError: Cannot read property 'content-type' of undefined

I'm running my build in Gulp and keep getting the following error in my terminal when it comes to generating my critical css files.
[08:47:29] -> Generating critical CSS: https://example.com/ -> ./templates/index_critical.min.css
[08:47:43] TypeError: Cannot read property 'content-type' of undefined
What does the error mean?
How do I solve the error?
If this is a syntax issue in my gulp file - is there way to find the line and reference to the issue either in the terminal when running the command or by using a validator?
Below is the gulp task for the critical css along with the tasks for processing the css and sass files which it references.
// scss - build the scss to the build folder, including the required paths, and writing out a sourcemap
gulp.task("scss", () => {
$.fancyLog("-> Compiling scss");
return gulp.src(pkg.paths.src.scss + pkg.vars.scssName)
.pipe($.plumber({errorHandler: onError}))
.pipe($.sourcemaps.init({loadMaps: true}))
.pipe($.sass({
includePaths: pkg.paths.scss
})
.on("error", $.sass.logError))
.pipe($.cached("sass_compile"))
.pipe($.autoprefixer())
.pipe($.sourcemaps.write("./"))
.pipe($.size({gzip: true, showFiles: true}))
.pipe(gulp.dest(pkg.paths.build.css));
});
// css task - combine & minimize any distribution CSS into the public css folder, and add our banner to it
gulp.task("css", ["scss"], () => {
$.fancyLog("-> Building css");
return gulp.src(pkg.globs.distCss)
//.pipe(purgecss({
// content: [pkg.paths.templates + '*.twig']
// }))
.pipe($.plumber({errorHandler: onError}))
.pipe($.newer({dest: pkg.paths.dist.css + pkg.vars.siteCssName}))
.pipe($.print())
.pipe($.sourcemaps.init({loadMaps: true}))
.pipe($.concat(pkg.vars.siteCssName))
.pipe($.if(process.env.NODE_ENV === "production",
$.cssnano({
discardComments: {
removeAll: true
},
discardDuplicates: true,
discardEmpty: true,
minifyFontValues: true,
minifySelectors: true
})
))
.pipe($.header(banner, {pkg: pkg}))
.pipe($.sourcemaps.write("./"))
.pipe($.size({gzip: true, showFiles: true}))
.pipe(gulp.dest(pkg.paths.dist.css))
.pipe($.filter("**/*.css"))
.pipe($.livereload());
});
// Process the critical path CSS one at a time
function processCriticalCSS(element, i, callback) {
const criticalSrc = pkg.urls.critical + element.url;
const criticalDest = pkg.paths.templates + element.template + "_critical.min.css";
let criticalWidth = 1200;
let criticalHeight = 1200;
if (element.template.indexOf("amp_") !== -1) {
criticalWidth = 600;
criticalHeight = 19200;
}
$.fancyLog("-> Generating critical CSS: " + $.chalk.cyan(criticalSrc) + " -> " + $.chalk.magenta(criticalDest));
$.critical.generate({
src: criticalSrc,
dest: criticalDest,
penthouse: {
blockJSRequests: false,
forceInclude: pkg.globs.criticalWhitelist
},
inline: false,
ignore: [],
css: [
pkg.paths.dist.css + pkg.vars.siteCssName,
],
minify: true,
width: criticalWidth,
height: criticalHeight
}, (err, output) => {
if (err) {
$.fancyLog($.chalk.magenta(err));
}
callback();
});
}
// critical css task
gulp.task("criticalcss", ["css"], (callback) => {
doSynchronousLoop(pkg.globs.critical, processCriticalCSS, () => {
// all done
callback();
});
});
// Lean Production build
gulp.task("leanbuild", ["set-prod-node-env", "static-assets-version", "criticalcss"]);
This happens if the src param you pass into critical is invalid, and returns no response.

stylelint - Where are there examples to create your own plugin?

I have gone to the stylelint website, github and downloaded locally via npm. The stylelint website advises that to create my own plugin I should use this format:
var myPluginRule = stylelint.createPlugin(ruleName, function(primaryOption, secondaryOptionObject) {
return function(postcssRoot, postcssResult) {
var validOptions = stylelint.utils.validateOptions(postcssResult, ruleName, { .. })
if (!validOptions) { return }
// ... some logic ...
stylelint.utils.report({ .. })
}
})
When I do a 'find' inside the npm folder for stylelint, I cannot find any examples that use this format. Can anyone advise a really good tutorial on creating your own plugin?
thanks
ok after playing around with it I have literally found a way.
1) prerequisites:
$ npm init
$ npm install gulp stylelint gulp-style-lint --save-dev
2) Create some scss files at ./scss/myfile.scss
body{background:red;}
3) create ./gulpfile.js
var gulp = require('gulp');
var gulpStylelint = require('gulp-stylelint');
gulp.task('stylelint',function(){
return gulp
.src('./scss/*.scss')
.pipe(
gulpStylelint({
reporters: [
{formatter: 'string', console: true}
]
})
);
})
4) create ./stylelintCustom/index.js
var stylelint = require("stylelint");
var ruleName = "steves/steve1";
var messages = stylelint.utils.ruleMessages(ruleName, {
rejected: 'steve rejects this',
});
module.exports = stylelint.createPlugin(ruleName, function(max, options) {
return function(root, result) {
// to access the variable for the whole of this file scss =
console.log(root.source.input);
// apply rules now...
// run reporter to output
}
});
module.exports.ruleName = ruleName;
module.exports.messages = messages;
Being sure to name ruleName: "plugins/plugin". ie steves/steverule1 etc.
5) Be sure to create stylelintCustom/package.json
{
"name": "stylelint-steves-steve1",
"version": "0.0.1",
"main": "index.js",
"devDependencies": {
"stylelint": "~2.6.0"
},
"engines": {
"node": ">=0.10.0"
}
}
6) create: stylelint.rc
{
"plugins": [
"./stylelintCustom/index.js"
],
"rules": {
"steves/steve1": true
}
}
7) run gulp
$ gulp stylelint
Will output the scss, so you can run whatever js, regex you need here.
For reference of how the existing rules work in stylelint you can go to:
yourproject/node_modules/stylelint/dist/rules/*

e2e browser opens and close immedietly

I am trying to test my app and followed this link http://lathonez.github.io/2016/ionic-2-e2e-testing/ i merged my app with firebase. Everything worked good, but when i run npm run e2e browser opens and close immediately in my terminal pops an error.
I followed this link http://lathonez.github.io/2016/ionic-2-e2e-testing/
Actually my issue is that i could not able to see any action takes place in my e2e browser could some on help me
protractorconfig.js
exports.config = {
baseUrl: 'http://192.168.1.2:8100/',
specs: [
'../app/pages/home/home.e2e.ts',
'../app/pages/Admin/admin.e2e.ts',
//'../app/pages/Listing/lisitngPage.e2e.ts'
],
exclude: [],
framework: 'jasmine2',
allScriptsTimeout: 110000,
jasmineNodeOpts: {
showTiming: true,
showColors: true,
isVerbose: false,
includeStackTrace: false,
defaultTimeoutInterval: 400000
},
directConnect: true,
chromeOnly: true,
capabilities: {
'browserName': 'chrome',
'chromeOptions': {
'args': ['--disable-web-security']
}
},
onPrepare: function() {
var SpecReporter = require('jasmine-spec-reporter');
jasmine.getEnv().addReporter(new SpecReporter({displayStacktrace: true}));
browser.ignoreSynchronization = false;
},
useAllAngular2AppRoots: true
};
gulpfile.ts
import { join } from 'path';
const config: any = {
gulp: require('gulp'),
appDir: 'app',
testDir: 'test',
testDest: 'www/build/test',
typingsDir: 'typings',
};
const imports: any = {
gulp: require('gulp'),
runSequence: require('run-sequence'),
ionicGulpfile: require(join(process.cwd(), 'gulpfile.js')),
};
const gulp: any = imports.gulp;
const runSequence: any = imports.runSequence;
// just a hook into ionic's build
gulp.task('build-app', (done: Function) => {
runSequence(
'build',
(<any>done)
);
});
// compile E2E typescript into individual files, project directoy structure is replicated under www/build/test
gulp.task('build-e2e', ['clean-test'], () => {
let typescript: any = require('gulp-typescript');
let tsProject: any = typescript.createProject('tsconfig.json');
let src: Array<any> = [
join(config.typingsDir, '/index.d.ts'),
join(config.appDir, '**/*e2e.ts'),
];
let result: any = gulp.src(src)
.pipe(typescript(tsProject));
return result.js
.pipe(gulp.dest(config.testDest));
});
// delete everything used in our test cycle here
gulp.task('clean-test', () => {
let del: any = require('del');
// You can use multiple globbing patterns as you would with `gulp.src`
return del([config.testDest]).then((paths: Array<any>) => {
console.log('Deleted', paths && paths.join(', ') || '-');
});
});
// run jasmine unit tests using karma with PhantomJS2 in single run mode
gulp.task('karma', (done: Function) => {
let karma: any = require('karma');
let karmaOpts: {} = {
configFile: join(process.cwd(), config.testDir, 'karma.config.js'),
singleRun: true,
};
new karma.Server(karmaOpts, done).start();
});
// run jasmine unit tests using karma with Chrome, Karma will be left open in Chrome for debug
gulp.task('karma-debug', (done: Function) => {
let karma: any = require('karma');
let karmaOpts: {} = {
configFile: join(process.cwd(), config.testDir, 'karma.config.js'),
singleRun: false,
browsers: ['Chrome'],
reporters: ['mocha'],
};
new karma.Server(karmaOpts, done).start();
});
// run tslint against all typescript
gulp.task('lint', () => {
let tslint: any = require('gulp-tslint');
return gulp.src(join(config.appDir, '**/*.ts'))
.pipe(tslint())
.pipe(tslint.report('verbose'));
});
// build unit tests, run unit tests, remap and report coverage
gulp.task('unit-test', (done: Function) => {
runSequence(
['lint', 'html'],
'karma',
(<any>done)
);
});

Resources