Mocha with babel transpile 3rd party dependencies - reactjs

I have a react native app that is setup with Redux and Redux Saga.
I have unit tests using mocha, all tests used to work fine until I added native-base.
When I test now, it throws this error
[poject-path]/node_modules/native-base-shoutem-theme/index.js:1
(function (exports, require, module, __filename, __dirname) { import connectStyle from './src/connectStyle';
^^^^^^
I have a setup with babel, is there anyway I can transpile that dependency? or do something without changing my code?
What I currently did in my file that is causing the problem is the following
const Toast = null;
if(process.env.NODE_ENV !== 'test')
Toast = require('native-base').Toast;
The tests work with the above, but I was just testing to make sure it passes and it did, however that's not a good way to do it.
There is a similar problem in their GitHub Repo here
Can anyone help?

I have a setup with babel, is there anyway I can transpile that dependency
By convention, all npm modules should be provided in repository in transplated form, usually, by perform prepublush script and index link into dist directory. But in general case babel can easily transplate any dependencies, by customizing ignore regex in configutation
For example, when using webpack with babel-loader, config with force transpiling MODULE_ONE and MODULE_TWO will have following view:
{
test: /(\.js)$/,
exclude: /node_modules(?!(?:\/|\\)((MODULE_ONE)|(MODULE_TWO)))/,
loader: 'babel',
query: { presets: ['react', 'es2015', 'stage-0'] }
}

Related

Syntax Error In IE 11 for this node_moduels

I am getting a syntax error in IE when this component of react is loaded in the webpage. Has anybody got the same problem? This is an inherited package, and a syntax error from node_modules makes no sense?
"use strict";
/* WEBPACK VAR INJECTION */(function(module) {
const colorConvert = __webpack_require__(/*! color-convert */ "./node_modules/color-convert/index.js");
const wrapAnsi16 = (fn, offset) => function () {
const code = fn.apply(colorConvert, arguments);
return `\u001B[${code + offset}m`;
};
const wrapAnsi256 = (fn, offset) => function () {
const code = fn.apply(colorConvert, arguments);
return `\u001B[${38 + offset};5;${code}m`;
};
If you are using newer versions of Node/NPM, check your package.json file -> "browserslist" section.
This is the default "browserslist" created for you if you do not have one defined:
In this case, if you run "npm start" on your LOCAL Environment, Babel will not create Polyfills for IE11 because its not included as a target browser in "development". To get this working, I deleted my node_modules directory completely, ran 'npm install', updated package.json with:
and ran 'npm start.
The reason why this fails is that babel or your other favorite transpiler might ignore node_modules (if that's how its configured), so you need to include it manually because IE does not support arrow function syntax.
First, if you search for wrapAnsi16 or wrapAnsi256 function names online it'll point you to common npm packages, such as: ansi-styles, chalk or color-convert, debug, strip-ansi, etc.
If you are using Webpack you can add the following to your rules:
module: {
rules: [{
exclude: /node_modules\/(?!(color-convert|ansi-styles|strip-ansi|ansi-regex|debug|react-dev-utils|chalk)\/).*/
}]
}
or, easier to read:
module: {
rules: [{
include: [
path.resolve(__dirname, 'node_modules/ansi-styles'),
path.resolve(__dirname, 'node_modules/strip-ansi'),
... other's here...
path.resolve(__dirname, 'src'),
]
}]
}
Hope this helps somebody in the future ;)
TLDR; you don't need this library, just run
npm run build
And it will be excluded from your build.
I have same problem with create-react-app, and I solve it (no). From my discovery, this library should not appear in browser, because it was designed for nodejs environment. Also I found, this library come to me as dependency of jest, and jest is dependency for tests and it come as dependency for react.
So, I run
npm run build
server -s build
And try my application in IE. And it work. So, when you run
npm start
It make file including dev dependencies and other garbage that should not appear in production and in browser at all. When you run
npm run build
It make file only with required project libraries.
I had similar issue #punkbit solution and installing 'react-app-polyfill'
and importing it at the top of the index.js file solved it
import 'react-app-polyfill/ie11';
import 'react-app-polyfill/stable';
If it still does not work delete node-modules and reinstall also clear cache in IE.
All the best :)
This problem occurs because your compiled code contains (modern) ES6 syntax whilst IE11 only supports ES5.
A way to fix this is to instruct webpack to specifically compile the mentioned packages into ES5;
module: {
rules: [{
test: /\.(tsx?|js)$/,
include: [
// These dependencies have es6 syntax which ie11 doesn't like.
// Whenever you see a "SyntaxError" that crashes IE11 because of a new lib, add it here.
path.join(__dirname, 'node_modules/react-intl'),
path.join(__dirname, 'node_modules/pkce-challenge'),
path.join(__dirname, 'node_modules/fuse.js')
],
use: [{
loader: 'ts-loader', // Or whatever loader you're using
}]
}]
}
for me this was: fuse.js, pkce-challenge and react-intl.

Webpack + Angular2 AOT: Uncaught SyntaxError: Unexpected token import

in this set-up, how do you transpile the angular2 library being imported from the generated ngfactory files?
the current app is a combination of the webpack + aot cookbook based on the angular docs
angular.io/docs/ts/latest/cookbook/aot-compiler.html
angular.io/docs/ts/latest/guide/webpack.html
I have a working POC where you can replicate the issue from this repo:
https://github.com/jetlogs/Angular2-AOT-Localization
after you've done the compilation / bundling, you can open the 2 files:
non-aot.html - this is the non-aot version of the same app, and it loads fine
aot.html - this file fails with:
ng_module_factory.js?95b1:13 Uncaught SyntaxError: Unexpected token import
Expected behavior
the expected behavior is that aot.html and non-aot.html should have the same behavior
Minimal reproduction of the problem with instructions
clone the repo, then
run these commands on the working directory:
npm install
npm postinstall
npm run build
then open aot.html to reproduce the issue
Is there any way on how to fix the import statements from the imported angular2 libraries? Thanks
UPDATE:
I've tried transpiling the angular2 source files which are in ES2015 by using the babel-loader:
{
test: /\.js$/,
loader: 'babel',
include: [
/node_modules(\\|\/)#angular/
],
exclude: [
/\.umd\.js$/
],
query: {
presets: ['es2015']
}
},
it now compiles without issues with ES6 incompatibilities, however, it now encounters a new error only for aot.html:
core.umd.js?e2a5:3272Uncaught Error: No provider for NgZone!
any reason why transpiled angular2 source codes being referenced by the AOT compiler are cdausing NgZone issues?
I've updated the repo above to reflect my latest changes
UPDATE2: 10/13/16
Updated to Angular 2.1
still the same issue
The System.import syntax used in ng_module_factory.js is ES6 style module loading. Webpack 1, which you are probably using, does not support this syntax.
A workaround might be to transpile the Angular ES6 modules to ES5 with require() syntax, but you already tried this without success.
However you might consider switching to Webpack 2, which fully supports ES6 style imports and is very close to its stable release. The compilation worked for me this way without changing anything except for the webpack config which uses a new syntax for some parts.
For me it was a wrong import generated by IDE:
import { Component, Output } from "#angular/core/src/metadata/directives";
Instead of:
import { Component, Output } from "#angular/core";

How to bundle ES6 based React components and keep the bundle in ES6, using webpack?

How can I use webpack to bundle Reactjs components that use ES6? The resulting bundle should be in ES6, it should not be transpiled to ES5.
There are a lot of good Reactjs/webpack examples available but all that I've found transpile to ES5.
Just run babel-loader without the ES2015 preset and add the transform-react-jsx plugin:
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /(node_modules|bower_components)/,
loader: 'babel',
query: {
plugins: ['transform-react-jsx']
}
}
]
}
I found this very nice example on how to configure Webpack with React and more: https://github.com/krasimir/react-webpack-starter. It uses ES6, including ES6 imports, but transpiles down to ES5.
By hacking the babel preset, I managed to get it to spit out ES6 bundled code. I changed the file node_modules/babel-preset-es2015 to:
module.exports = {
plugins: [
require("babel-plugin-transform-es2015-modules-commonjs")
]
};
This is of course not an acceptable solution, what one needs to do is to find or create Bable preset that contains this.
The first thing I notice after this, was that UglifyJS doesn't support ES6. I suspect that there will be other issues down the road, so newbies like my self should perhaps stick to transpiling to ES5 a little bit longer.

How to transpile a Relay query from TypeScript to ES5?

I'm writing a web app in TypeScript. The app uses React and Relay from Facebook.
My TypeScript source code gets compiled into ES6 code using the TypeScript compiler TSC. Then, the ES6 code gets transpiled into ES5 code using Babel. In order for Relay to work in the browser, a Babel plugin needs to transform the Relay GraphQL queries: https://facebook.github.io/relay/docs/guides-babel-plugin.html. The problem is, because TSC first transpiles these queries, the Babel Relay plugin doesn't recognize them anymore so they don't get transpiled into something the browser understands, so the browser throws an error:
Uncaught Invariant Violation: RelayQL: Unexpected invocation at
runtime. Either the Babel transform was not set up, or it failed to
identify this call site. Make sure it is being used verbatim as
Relay.QL.
My TypeScript source code:
const SiteQuery = {
store: () => Relay.QL`query { site }`
};
... this gets compiled by TSC into something like this:
var SiteQuery = {\r\n store: function () { return (_a = [\"query { site }\"], _a.raw = [\"query { site }\"], Relay.QL(_a)); var _a; }\r\n};
... instead of something like this (because the Babel Relay plugin doesn't do its work properly):
var SiteQuery = {\n store: function store() {\n return (function () {\n return {\n fieldName: 'site',\n kind: 'Query',\n metadata: {},\n name: 'Router',\n type: 'Site'\n };
This is because the Babel Relay plugin doesn't recognize the transpiled version, and as a result it doesn't transpile the query into something the browser understands.
How to make this work?
The answers here were helpful, but I thought I'd share what finally worked for me.
Setup your babel-relay-plugin correctly. If you're running into problems here, I recommend using the npm package babel-relay-plugin-loader which then allows you to specify the location of your schema.json in package.json. For example:
{ "metadata": { "graphql": { "schema": "./schema.json" } } }
Setup your babel config correctly. It should look something like this:
{
"passPerPreset": true,
"presets": [
"react",
"es2015",
"stage-0"
],
"plugins": [
"babel-relay-plugin-loader"
]
}
},
Setup your tsconfig to target "es6" -- this actually was essential to make my setup work. ts-loader then compiles to es6 and Babel handles the transpile down to es5.
Finally, add the loaders to your webpack config. Remember, it applies these RIGHT to left. So, mine looks like this:
loaders: [
{
test: /.tsx?$/,
exclude: /node_modules/,
loader: 'react-hot!babel!ts-loader',
},
],
You need to tell the Typescript compiler to transpile to ES6, then use Babel with babel-relay-plugin and es2015 preset to transpile the code to ES5 to run in your browser.
I recommend using Webpack to orchestrate all this. These will get you started:
http://www.jbrantly.com/typescript-and-webpack/
http://www.jbrantly.com/es6-modules-with-typescript-and-webpack/
The posts were written for Babel 5.x, so you'll need to manually add es2015 preset to make sure Babel compiles the ES6 sources to ES6.
Just in case, when you say
My TypeScript source code gets compiled into ES6 code using the TypeScript compiler TSC. Then, the ES6 code gets transpiled into ES5 code using Babel.
You can instruct TypeScript itself to transpile directly to es5, just set target: 'es5' in tsconfig.json and that's it, hope it helps since you can eliminate babel from your compile chain.

React webpack undefined react in console

I have problem with webpack build I write custom webpack config:
https://github.com/Simproduction/react-client-webpack
but when I run dev or build a project everything work correct but I can't call React from console or use react developers tools
I get error
Uncaught ReferenceError: React is not defined(…)
Could you help me?
My test project,
https://github.com/Simproduction/react-CM
You need to expose React so it is available on the window using the expose-loader:
module: {
loaders: [
{ test: require.resolve("react"), loader: "expose?React" },
]
}
It contains AMD and CommonJS in webpack. You know js loader, right?
If you use AMD ,you know that all js code are in 'define([],function(){ var a=10; ...}) area. if you want print a in console. You should like this
define([],function(){
var a=10;
window.a = a;
})
so, you can edit your main.js. Add this line window.React = React; , but we may use CDN instead of it is common solution.

Resources