Can not transform code with babel transform with config file - babeljs

This is the config file:
{
"presets": [
"#babel/preset-env"
],
"plugins": [
"#babel/plugin-transform-modules-commonjs"
]
}
This is the command:
npx babel src/* --out-dir build
The CLI output is
src/script.js -> build\src\script.js
The output script file is identical to the input script file.
This is the node.js file:
const babel = require('#babel/core');
const fs = require('fs');
fs.writeFileSync(
'build/index.js',
babel.transformFileSync(
'src/index.js',
{
plugins: ["#babel/plugin-transform-modules-commonjs"]
}
).code
);
The output script file's content is what is expected.
I used this as input:
const test = 0;
export default { test };
This is the output from the CLI command shown above.
const test = 0;
export default { test };
This is the output from the NodeJS file shown above (which is my expected output from the CLI).
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports["default"] = void 0;
var test = 0;
var _default = {
test: test
};
exports["default"] = _default;
Q: Can you you babel CLI to transform code?

We have used babel-node in scenario where we want to transpile. https://babeljs.io/docs/en/next/babel-node.html
npx babel-node src/* --out-dir build

Not sure why transform, which is an async function, is being used inside a synchroous, blocking execution. Instead use transformSync and .code
fs.writeFileSync(
'build/script.js',
babel.transformSync(
fs.readFileSync('src/script.js').toString('utf8'),
{
plugins: ["#babel/plugin-transform-modules-commonjs"]
}
).code
);
Or even more, you can use transformFileSync:
fs.writeFileSync(
'build/script.js',
babel.transformFileSync(
'src/script.js',
{
plugins: ["#babel/plugin-transform-modules-commonjs"]
}
).code
);

Related

How to integrate Material UI into Svelte project

I want to integrate Material UI into my Svelte project.
I tried to follow the official documentation from here, but I don't know why I'm getting a strange error while trying to run my project:
loaded rollup.config.js with warnings
(!) Unused external imports
default imported from external module 'rollup-plugin-postcss' but never used
rollup v1.27.13
bundles src/main.js → public/build/bundle.js...
[!] Error: Unexpected token (Note that you need plugins to import files that are not JavaScript)
src/views/App.css (1:0)
1: .footer.svelte-1xl6ht0{position:fixed;left:0;bottom:0;width:100%;background-color:#569e3e;color:white;text-align:center;height:15px}.footer.us.svelte-1xl6ht0,.footer.europe.svelte-1xl6ht0,.footer.central.svelte-1xl6ht0,.footer.south.svelte-1xl6ht0,.footer.apac.svelte-1xl6ht0,.footer.baldr.svelte-1xl6ht0{background-color:#ca4a4a}.footer
....
The problem seems to be related to CSS.
In my src directory I have a directory called theme which contains a file called _smui-theme.scss and this is the content of the file:
#import "#material/theme/color-palette";
// Svelte Colors!
$mdc-theme-primary: #ff3e00;
$mdc-theme-secondary: #676778;
// Other Svelte color: #40b3ff
$mdc-theme-background: #fff;
$mdc-theme-surface: #fff;
$mdc-theme-error: $material-color-red-900;
And here is my rollup.config.json file:
import svelte from 'rollup-plugin-svelte';
import resolve from 'rollup-plugin-node-resolve';
import commonjs from 'rollup-plugin-commonjs';
import livereload from 'rollup-plugin-livereload';
import { terser } from 'rollup-plugin-terser';
import json from '#rollup/plugin-json';
const production = !process.env.ROLLUP_WATCH;
export default {
input: 'src/main.js',
output: {
sourcemap: true,
format: 'iife',
name: 'app',
file: 'public/build/bundle.js',
},
plugins: [
json(),
svelte({
// Enables run-time checks when not in production.
dev: !production,
// Extracts any component CSS out into a separate file — better for performance.
css: css => css.write('public/build/bundle.css'),
// Emit CSS as "files" for other plugins to process
emitCss: true,
}),
resolve({
browser: true,
dedupe: importee => importee === 'svelte' || importee.startsWith('svelte/')
}),
commonjs(),
// In dev mode, call `npm run start` once the bundle has been generated
!production && serve(),
// Watches the `public` directory and refresh the browser on changes when not in production.
!production && livereload('public'),
// Minify for production.
production && terser()
],
watch: {
clearScreen: false
}
};
function serve() {
let started = false;
return {
writeBundle() {
if (!started) {
started = true;
require('child_process').spawn('npm', ['run', 'start', '--', '--dev'], {
stdio: ['ignore', 'inherit', 'inherit'],
shell: true
});
}
}
};
}
In order to solve this issue a postcss plugin is needed for rollup.
I have also added a svelte preprocessor (I think this is optional, but I wanted to be sure).
Make sure you install this packages with npm or yarn:
rollup-plugin-postcss and svelte-preprocess
Then the plugins should be added in rollup.config.js like this:
import svelte from 'rollup-plugin-svelte';
import resolve from 'rollup-plugin-node-resolve';
import commonjs from 'rollup-plugin-commonjs';
import livereload from 'rollup-plugin-livereload';
import { terser } from 'rollup-plugin-terser';
import postcss from 'rollup-plugin-postcss'; <<<------------- Add this
import autoPreprocess from 'svelte-preprocess'; <<<------------- Add this
import json from '#rollup/plugin-json';
const production = !process.env.ROLLUP_WATCH;
export default {
input: 'src/main.js',
output: {
sourcemap: true,
format: 'iife',
name: 'app',
file: 'public/build/bundle.js',
},
plugins: [
json(),
svelte({
// Enables run-time checks when not in production.
dev: !production,
// Extracts any component CSS out into a separate file — better for performance.
css: css => css.write('public/build/bundle.css'),
// Emit CSS as "files" for other plugins to process
emitCss: true,
preprocess: autoPreprocess() <<<------------- Add this
}),
resolve({
browser: true,
dedupe: importee => importee === 'svelte' || importee.startsWith('svelte/')
}),
commonjs(),
postcss({ <<<------------- Add this
extract: true,
minimize: true,
use: [
['sass', {
includePaths: [
'./src/theme',
'./node_modules'
]
}]
]
}),
// In dev mode, call `npm run start` once the bundle has been generated
!production && serve(),
// Watches the `public` directory and refresh the browser on changes when not in production.
!production && livereload('public'),
// Minify for production.
production && terser()
],
watch: {
clearScreen: false
}
};
function serve() {
let started = false;
return {
writeBundle() {
if (!started) {
started = true;
require('child_process').spawn('npm', ['run', 'start', '--', '--dev'], {
stdio: ['ignore', 'inherit', 'inherit'],
shell: true
});
}
}
};
}
Now everything should be working right with the css and Material UI can be used.

How we can generate html report in cucumber latest version(3.2.0) with protractor-cucumber framework

Since cucumber 3 removed the registerHandler and registerListener , how we can generate html report in cucumber 3.2.0.I have used below code for generating json report in cucumber 2.
defineSupportCode(function({ registerListener }) {
var JsonFormatter = new Cucumber.JsonFormatter();
JsonFormatter.log = function(string) {
var outputDir = 'testreports/report';
var fileName = 'cucumber-report.json';
var targetJson = path.resolve(outputDir, fileName);
if (fse.existsSync(outputDir)) {
fse.moveSync(outputDir, outputDir + '_' + moment().format('YYYYMMDD_HHmmss'), {
overwrite: true
});
}
fse.outputFileSync(targetJson, string);
};
registerListener(JsonFormatter);
});
and used below code for html report
defineSupportCode(function({ registerHandler }) {
registerHandler('AfterFeatures', function(features, callback) {
var options = {
theme: 'bootstrap',
jsonFile: 'testreports/report/cucumber-report.json',
output: 'testreports/report/cucumber-report.html',
reportSuiteAsScenarios: true,
};
reporter.generate(options);
callback();
});
});
Thanks in advance.
You have to do following changes:
1) set cucumberOpts.format in protractor conf file
cucumberOpts: {
format: ["json:reports/report/cucumber/cucumber-report.json"],
here reports/report/cucumber/cucumber-report.json is the cucumber json file path, you must specify a path at here.
framework will generate it automatically with results' json data as file content when all scenarios execute complete.
2) create parent folder of cucumber json file path before test framework load if parent folder not exist
Option 1: put create parent folder code at head of protractor conf file.
Option 2: create a Protractor plugin implement interface: setup(), which will be executed before test framework load.
// plugin: create-report-folder.js
var moment = require("moment");
var fse = require("fs-extra");
module.exports = {
setup: function() {
var reportDir = this.config.options.reportDir;
if (fse.existsSync(reportDir)) {
fse.moveSync(
reportDir,
reportDir + "_" + moment().format("YYYYMMDD_HHmmss"),
{ overwrite: true}
);
}
fse.mkdirsSync(reportDir);
}
};
Note: both options need to use Sync api to create folder.
3) create Protractor plugin implement interface: postResults which will be executeed after all scenarios execute complete.
// plugin: cucumber-html-reporter.js
var reporter = require("cucumber-html-reporter");
module.exports = {
postResults: function() {
var options = {
theme: "bootstrap",
jsonFile: this.config.options.jsonFile,
output: this.config.options.htmlFile,
reportSuiteAsScenarios: true
};
reporter.generate(options);
}
};
Note: I tried generate cucumber html report in cucumber AfterAll hook, but failed, seems Cucumber JsonFormater generate cucumber json file is Async, when AfterAll hook start execute, cucumber json file have not create yet.
I'm keeping look into formatOption, should be a way to change JsonFormater generate cucumber json file to Sync, then we can use AfterAll hook.
4) set plugins in protractor conf file
// protractor conf file
exports.config = {
plugins: [
// plugin to create report parent folder
{
path: "supports/create-report-folder.js",
options: {
reportDir: "reports/report/cucumber"
}
}
// plugin to generate cucumber html report
{
path: "supports/cucumber-html-reporter.js",
options: {
jsonFile: "reports/report/cucumber/cucumber-report.json",
htmlFile: "reports/report/cucumber/cucumber-report.html"
}
}
]
A workable scaffold for Protractor + Cucumber4 + HTML Report at my github
The scaffold for Protractor + Cucumber3 + HTML Report on my local has some dependency campatible issue, I'm looking into that in case you must use Cucumber 3.
5) If you use multiCapabilities, you can use below package to generate report:
protractor-multiple-cucumber-html-reporter-plugin
If the location of protractor.conf.js is not at the same level as node_modules then the cucumberOpts.format path would be relative to its current file location and the protractor-multiple-cucumber-html-reporter-plugin looks for the json files relative to parent root folder and warns about json file is not found.
To solve this provide absolute path of the json file to cucumberOpts.format like below. This is applicable if you're using cucumber for e2e testing in Angular applications where the protractor.conf.js is normally present inside e2e folder.
cucumberOpts: {
require: [path.resolve(process.cwd(), 'e2e/steps/*.ts')],
format: 'json:'+ path.resolve(process.cwd() + '/reports/cucumber-ui-reports.json')
}

Webpack with Babel lazy load module using ES6 recommended Import() approach not working

I'm trying to do code splitting and lazy loading with webpack using the import() method
import('./myLazyModule').then(function(module) {
// do something with module.myLazyModule
}
I'm getting
'import' and 'export' may only appear at the top level
Note top level imports are working fine, i'm just getting an issue when I try and using the dynamic variant of import()
var path = require('path');
module.exports = {
entry: {
main: "./src/app/app.module.js",
},
output: {
path: path.resolve(__dirname, "dist"),
filename: "[name]-application.js"
},
module: {
rules: [
{
test: /\.js$/,
use: [{
loader: 'babel-loader',
query: {
presets: ['es2015']
}
}]
}
]
},
resolve : {
modules : [
'node_modules',
'bower_components'
]
},
devtool : "source-map"
}
EDIT:
If I change it so the syntax reads, it works.... but the chunk comments don't work to label the bundle. I'm confused because the documentation says the the following is depreciated.
The use of System.import in webpack did not fit the proposed spec, so
it was deprecated in webpack 2.1.0-beta.28 in favor of import().
System.import('./myLazyModule').then(function(module) {
// do something with module.myLazyModule
}
You need the plugin syntax-dynamic-import to be able to use the import() function with Babel.
Install it with:
npm install --save-dev #babel/plugin-syntax-dynamic-import
And add it to your plugins:
{
presets: ['es2015'],
plugins: ['#babel/plugin-syntax-dynamic-import']
}

access browserify -r params in karma

I call browserify with npm from the package.json scripts block. Here's an abbreviated version of the script.
"build:js": "browserify -r ./config.js:config -e -d src/index.js > build/index.js"
Everything works great. Inside index.js, I just refer to this parameter using: require('config') and browserify does the rest.
Now I'm trying to set up karma with browserify for testing, and karma-browserify can't find that variable. I've looked around and haven't found much, but tried to add require: ['./src/app/config/config-dev.js'] to my karma.conf.js inside the browserify object, like so:
browserify: {
debug: true,
require: ['./src/app/config/config-dev.js']
}
But karma doesn't make the connection between the require statement in the index to the parameter file, if nothing else, then because it isn't named. What I need to know is the syntax for karma when I use browserify CLI to add a param.
Any pointers to documentation explaining this or ideas about what I could try here would be super helpful. Thanks!
Try adding your require resolution to your package.json under the "browser" field.
E.g.:
"browser": {
"config": "./config"
}
If you’re trying to have a different config based on your environment then you could do:
./config.js:
if (process.env.NODE_ENV === 'production') {
module.exports = { /* production config */ };
} else if (process.env.NODE_ENV === 'development') {
module.exports = { /* development config */ };
} else if (process.env.NODE_ENV === 'test') {
module.exports = { /* test config */ };
}
then in your package.json you would have something like:
"scripts": {
"build:js": "NODE_ENV=production browserify -d -e src/index.js",
"test": "NODE_ENV=test karma"
},
"browserify": {
"transform": [
"envify"
]
}
envify being a crucial part which allows you to replace environment variables with their string directly in the code. e.g.: process.env.NODE_ENV === 'development' might become simply 'development' === 'development'. Such things can then be removed with a minification tool like uglifyjs.

How do I parameterize the baseUrl property of the protractor config file

I need to run my protractor tests in different contexts with different baseUrls in the config files. I don't want to use separate config files for each situation since that is more difficult to maintain. Rather, I want to pass the base url in as a command line parameter. Here is what I have tried so far:
The protractor.conf.js:
exports.config = {
onPrepare : {
...
exports.config.baseUrl = browser.params.baseUrl;
...
}
}
And to invoke protractor:
protractor protractor.conf.js --params.baseUrl 'http://some.server.com'
This does not work since it seems like the browser instance is already configured before onPrepare is called.
Similarly, I have tried this:
exports.config = {
baseUrl : browser.params.baseUrl
}
But this doesn't work either since it seems like the browser instance is not available when the config is being generated.
It looks like I can use standard node process.argv to access all command line arguments, but that seems to be going against the spirit of protractor.
What is the best way for me to do what I need to do?
Seems like this is already possible, but the documentation is spotty in this area. Looking at the code, however, protractor does support a number of seemingly undocumented command line arguments.
So, running something like this will work:
protractor --baseUrl='http://some.server.com' my.conf.js
The other option is to use gruntfile.js and have it call the protractor config file.
//gruntfile.js
module.exports = function (grunt) {
grunt.registerTask("default", "", function () {
});
//Configure main project settings
grunt.initConfig({
//Basic settings and infor about our plugins
pkg: grunt.file.readJSON('package.json'),
//Name of plugin
cssmin: {
},
protractor: {
options: {
configFile: "conf.js", // Default config file
keepAlive: true, // If false, the grunt process stops when the test fails.
noColor: false, // If true, protractor will not use colors in its output.
args: {
baseUrl: grunt.option('baseUrl') || 'http://localhost:6034/'
}
},
your_target: { // Grunt requires at least one target to run so you can simply put 'all: {}' here too.
options: {
configFile: "conf.js", // Target-specific config file
args: {
baseUrl: grunt.option('baseUrl') || 'http://localhost:63634/'
}
}
},
},
//uglify
uglify: {
}
});
//Load the plugin
grunt.loadNpmTasks('grunt-contrib-cssmin');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-protractor-runner');
//Do the Task
grunt.registerTask('default', ['cssmin']);
};
the Protractor config file: conf.js
exports.config = {
directConnect: true,
// Capabilities to be passed to the webdriver instance.
capabilities: {
'browserName': 'chrome',
'chromeOptions': {
args: ['--no-sandbox']
}
},
chromeOnly: true,
// Framework to use. Jasmine is recommended.
framework: 'jasmine',
// Spec patterns are relative to the current working directory when
// protractor is called.
specs: ['specs/*/*_spec.js'],
suites : {
abcIdentity : 'specs/abcIdentity/*_spec.js' //picks up all the _spec.js files
},
params: {
UserName: 'abc#test.com',
Password: '123'
},
// Options to be passed to Jasmine.
jasmineNodeOpts: {
defaultTimeoutInterval: 30000,
includeStackTrace: true
},
onPrepare: function () {
browser.driver.manage().window().maximize();
if (process.env.TEAMCITY_VERSION) {
var jasmineReporters = require('jasmine-reporters');
jasmine.getEnv().addReporter(new jasmineReporters.TeamCityReporter());
}
}
};
//To run with default url http://localhost:6034
grunt protractor
//To run with any other url
grunt protractor --baseUrl:"http://dev.abc.com/"
I know, old one. but if anyone is still looking for a way to define a url based on capability (I had to do this because Ionic 5 will run in browser on port 8100, but in the app - unchangable - without port declaration on port 80, I use Appium)
add a baseUrl parameter inside your capability declaration.
{
browserName: 'chrome',
baseUrl: 'http://localhost:8100' //not required but as example
}
{
...
app: 'path to app.apk',
baseUrl: 'http://localhost'
...
}
and then configure your onPrepare method as follows.
async onPrepare() {
const config = await browser.getProcessedConfig();
if(config.capabilities.hasOwnProperty('baseUrl')) {
browser.baseUrl = config.capabilities.baseUrl;
}
}
OnPrepare runs for each capability you define in your multiCapabilities array. the getProcessedConfig returns the config as you defined it, with the addition of the current capability. Since that method returns a promise, I use async/await for readability.
This way, you can have multiple capabilities running, with each different a different host.
Base url should be declared baseUrl: "", in config.ts
I am using cucumber hooks and the below code is added in hooks file to pass the required url based upon the environments
if(browser.params.baseUrl==="QA"){
console.log("Hello QA")
await browser.get("https://www.google.com");
} else {
console.log("Hi Dev")
await browser.get("https://www.gmail.com");
}
run the tests using protractor command
protractor --params.baseUrl 'QA' typeScript/config/config.js --cucumberOpts.tags="#CucumberScenario"