Running Nighwatch.js with Babel 7 #babel/register - babeljs

I have a client repository with React 15.3, Webpack 4, and Babel 7. Webpack works as a charm, but our E2E testing suite using Nightwatch 0.9.20 fails to compile with the new #babel/register package.
Our company is upgrading our babel version from 6 to 7.
Floating around the internet a solution to add the following to the babel.config.js file:
{
"presets": [
[
"#babel/preset-env",
{
"modules": "commonjs",
"targets": {
"node": "current"
}
}
]
],
"plugins": [
"add-module-exports",
]
}
In our instance, this solution doesn't resolve our problem.
I should mention the structure of the project is as follows:
client // where nightwatch is run from the terminal
|-- tests // our E2E tests
|-- nightwatch.conf.js
|-- nighwatch_globals.js
|-- babel.config.js
api // a completely separate repository
|-- tests // we store factory definitions here as well
|-- db
|-- models // also a frequently referenced directory in our E2E tests
Our nightwatch.conf.js structure looks like this:
require('#babel/register')(); // this has been upgraded from 'babel-register'
require('dotenv').config();
...
module.exports = {
// nightwatch configurations
"globals_path": "./nightwatch_globals.js",
// more nightwatch configurations
}
Our nightwatch_globals.js file (where the error is being called looks like this:
import fetch from 'isomorphic-fetch';
module.exports = {
reporter: function(results, cb) {
fetch('http://localhost:4444/selenium-server/driver/?cmd=shutDownSeleniumServer').then(() => {
cb();
if (
(typeof(results.failed) === 'undefined' || results.failed === 0) &&
(typeof(results.error) === 'undefined' || results.error === 0)
) {
process.exit(0);
} else {
process.exit(1);
}
});
},
// give the db some time to finish ops from previous test before
// clearing db and starting the next test
before: function(done) {
require('./../eka-api/test/factories/index.js');
done();
},
beforeEach: function(done) {
setTimeout(function() {
done();
}, 5000);
},
};
And our babel.config.js file is the following:
module.exports = function(api) {
api.cache(true);
const presets = [
"#babel/preset-env",
"#babel/react",
"#babel/preset-flow",
];
const plugins = [
"#babel/plugin-syntax-flow",
"#babel/transform-flow-strip-types",
["#babel/plugin-proposal-decorators", {"legacy": true}],
// react hot loader must come before class properties plugin
"react-hot-loader/babel",
// class properties plugin must come after decorators
// if decorators has a 'legacy' attribute, class properties must be loose
["#babel/plugin-proposal-class-properties", {"loose" : true}],
"#babel/plugin-transform-runtime"
];
return {
presets,
plugins
};
};
From the client directory I run in the terminal node nightwatch.conf.js ; nightwatch
Here is the persisting error
/Users/myUser/Documents/api/test/factories/index.js:1
(function (exports, require, module, __filename, __dirname) { import bluebird from 'bluebird';
^^^^^^
SyntaxError: Unexpected token import
at createScript (vm.js:74:10)
at Object.runInThisContext (vm.js:116:10)
at Module._compile (module.js:533:28)
at Module._compile (/Users/myUser/Documents/eka-client/node_modules/pirates/lib/index.js:99:24)
at Module._extensions..js (module.js:580:10)
at Object.newLoader [as .js] (/Users/myUser/Documents/eka-client/node_modules/pirates/lib/index.js:104:7)
at Module.load (module.js:503:32)
at tryModuleLoad (module.js:466:12)
at Function.Module._load (module.js:458:3)
at Module.require (module.js:513:17)
My intuition tells me that the reason why the import token is not recognized has to do with how Babel 7 is scoping the compilation of code down to the process.cwd(). As you see the error is coming from the api. Since nightwatch is a package in the client directory, Babel isn't compiling the api directory (which is still on Babel 6). However, I'd like to avoid having to refactor our entire client testing suite to be independent of the api files.
I suspect the solution is to find a way for #babel/register to compile the api from the client side, but I don't know how I'd go about doing something like this.

Related

How to pass options to babel plugin transform-modules-commonjs?

I create a Vue 2 project by Vue-Cli 5, then I want to remove "use strick" in the complied code.
As I Know, the #babel/plugin-transform-strick-mode may be enabled via #babel/plugin-transform-modules-commonjs, and the plugin is included in #babel/preset-env under the modules option.
But the Vue-Cli used a preset #vue/babel-preset-app by a plugin #vue/cli-plugin-babel for babel.
So my question is How pass strictMode: false as an option to the transform-modules-commonjs by #vue/babel-preset-app which preset is in the #vue/cli-plugin-babel ?
module.exports = {
presets: [["#vue/cli-plugin-babel/preset", { modules: "auto" }]],
plugins: [
// I tried this way, but it throw many errors like:
/**
ERROR in ./node_modules/axios/dist/node/axios.cjs 11:15-32
Module not found: Error: Can't resolve 'stream' in 'D:\workspace\cqset_offical_website\node_modules\axios\dist\node'
BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.
If you want to include a polyfill, you need to:
- add a fallback 'resolve.fallback: { "stream": require.resolve("stream-browserify") }'
- install 'stream-browserify'
If you don't want to include a polyfill, you can use an empty module like this:
resolve.fallback: { "stream": false }
*/
["#babel/plugin-transform-modules-commonjs", {}],
[
"component",
{
libraryName: "element-ui",
styleLibraryName: "theme-chalk",
},
],
],
};

Unable to resolve module when using babel module resolver + eslint + index files in react application

I am trying to use babel module resolver plugin with eslint + create react app but I am unable to start the application, getting the error
internal/modules/cjs/loader.js:1237
throw err;
^
SyntaxError: C:\Users\enisr\Desktop\projects\pcPartPicker\jsconfig.json:
Unexpected token } in JSON at position 166
at parse (<anonymous>)
I have set up a git repo showcasing the problem https://github.com/sgoulas/pcPartPicker
I have read the instructions in the docs and in the original repository and I am unable to configure it correctly.
My configuration files are the following:
.babelrc
{
"plugins": [
["module-resolver", {
"extensions": [
".js",
".jsx",
".es",
".es6",
".mjs"
],
"root": ["./src"],
"alias": {
"#components": "./src/components"
}
}
]
]
}
jsconfig.json
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"*": ["src/*"],
"#components/*": ["./src/components/*"],
}
}
}
webpack.config.dev.js
var path = require("path");
module.exports = {
include: path.appSrc,
loader: require.resolve("babel-loader"),
options: {
plugins: [
[
"module-resolver",
{
root: ["./src/App"],
alias: {
"#components": "./src/components",
},
},
],
],
cacheDirectory: true,
},
};
My component:
import { GPUtable, CPUtable } from "#components/Tables";
const App = () => {
return (
<>
<GPUtable />
<CPUtable />
</>
);
};
export default App;
There are some minor fixes you need to make (below), but the main issue is that Create React App does not expose the webpack config, you'll need to eject to edit that.
npm run eject
Merge the babel configs: delete the babel key + value at the bottom of the package.json, and paste the value into your bablrc ("presets": ["react-app"],).
Add import React from 'react'; to the top of App.js
Confirmed locally that the app will run.
Other suggested fixes
Your jsconfig has a trailing comma after the array value in #components/*. You need to remove it because JSON doesn’t support them.
You need to fix the include path in weback.config.dev.js. appSrc isn't something defined on the node path module. Try using path.resolve(__dirname, 'src') - the example in their docs is creating/importing a paths object with appSrc pointing to this value.
You're missing test: /\.(js|jsx|mjs)$/, in webpack.config.dev.js.

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.

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']
}

MongoDB throwing error Module not found: 'module'

I have a Mongo db setup on localhost:27017 and and trying to connect to it from my app that uses Webpack via Mongoose. I have Mongoose installed as a package. Here is my code:
import mongoose from 'mongoose';
var db = mongoose.connect('mongodb://localhost:27017/music-app');
mongoose.connection.once('connected', function() {
console.log("Connected to database")
});
I'm pretty sure i've followed the documentation correctly but it's throwing the following compile error:
Error in ./~/mongoose/~/mongodb/~/mongodb-core/~/require_optional/~/resolve-from/index.js
Module not found: 'module' in C:\Users\new\Desktop\Development Projects\music-app\node_modules\mongoose\node_modules\mongodb\node_modules\mongodb-core\node_modules\require_optional\node_modules\resolve-from
There is also another error in the console:
webpackHotDevClient.js:216 Error in ./~/mongoose/~/mongodb/lib/mongo_client.js
Module not found: 'dns' in C:\Users\new\Desktop\Development Projects\music-app\node_modules\mongoose\node_modules\mongodb\lib
# ./~/mongoose/~/mongodb/lib/mongo_client.js 12:10-24
Anyone seen this before and know how to resolve it? Is there additional packages I might need to install in node?
This error is because you're trying to use mongodb from browser, as create-react-app is a front-end app.
You should use a back-end server and use mongodb from there.
You can check out this this full-stack repo having a nodejs server with create-react-app front-end.
https://github.com/fullstackreact/food-lookup-demo
That is because Webpack can’t statically analyze if (typeof window === 'undefined') in mongoose/lib/drivers/index.js
Here is the solution:
webpackConfig.plugins = [
...,
new webpack.DefinePlugin({
'typeof window': "\"object\""
}),
...
]
Also, if you get error messages regarding mongoose, check out below configurations.
npm install node-loader --save-dev
npm install require_optional --save-dev
npm install module --save-dev
webpack.config.js
const webpackConfig = {
name : 'client',
target : 'web',
devtool : config.compiler_devtool,
resolve : {
root : paths.client(),
extensions : ['', '.js', '.jsx', '.json', '.coffee', '.node']
},
node: {
fs: 'empty',
net: 'empty',
tls: 'empty'
},
module : {}
}
// ------------------------------------
// Loaders
// ------------------------------------
// JavaScript / JSON
webpackConfig.module.loaders = [{
test : /\.(js|jsx)$/,
exclude : /node_modules\/(?!(lodash-es)\/).*/,
loader : 'babel',
query : config.compiler_babel
}, {
test : /\.json$/,
loader : 'json'
}, {
test: /\.coffee$/,
loader: 'coffee-loader',
exclude: /node_modules|lib/
}, {
test: /\.node$/,
loader: 'node-loader'
}]