Using ES7 static propTypes with React-Native - react-native

When I'm launching my project using React-Native default packager, I have this error: Unexpected token on this line:
static propTypes = {
/// ...
};
I took a look on React-Native issues on GitHub, but I didn't find a solution.
Any suggestion?

React-Native packager use Babel for transfer ES6 and ES7, but NOT ALL features. The enable list is here. In your case, class-props is not enabled by default in RN packager. You can use Babel to compiler your code before packager, or just enable it in the packager setting. See this official doc for more information.

Try appending your propTypes to your class:
var MyClass extends React.Component {
....
}
MyClass.propTypes = {
.... /* enter proptypes here */
}

After #Fomahaut answer, I keep looking on Facebook's GitHub repository and found this issue: https://github.com/facebook/react-native/issues/2182
Create a .babelrc file at the project's root directory
Add more rules to Babel
Example:
{
"retainLines": true,
"compact": true,
"comments": false,
"whitelist": [
"es6.arrowFunctions",
"es6.blockScoping",
"es6.classes",
"es6.constants",
"es6.destructuring",
"es6.forOf",
"es6.modules",
"es6.parameters",
"es6.properties.computed",
"es6.properties.shorthand",
"es6.spread",
"es6.tailCall",
"es6.templateLiterals",
"es6.regex.unicode",
"es6.regex.sticky",
"es7.asyncFunctions",
"es7.classProperties",
"es7.comprehensions",
"es7.decorators",
"es7.exponentiationOperator",
"es7.exportExtensions",
"es7.functionBind",
"es7.objectRestSpread",
"es7.trailingFunctionCommas",
"regenerator",
"flow",
"react",
"react.displayName"
],
"sourceMaps": false
}

According to this answer, you need to install a plugin for class properties as of Babel 6.
As of Babel 6, you now need the transform-class-properties plugin to
support class properties.
Steps:
Run this: npm install babel-plugin-transform-class-properties
Add this to your .babelrc: "plugins": ["transform-class-properties"]
(Note, it's a plugin, not a transform; so don't put it in the "presets" list.)
Worked for me.

Install the stage-0 Babel preset (npm i --save-dev babel-preset-stage-0) and add it to .babelrc file's presets section, e.g.:
{ "presets": ["react", "es2015", "babel-preset-stage-0"] }

See if that helps:
$ npm install babel-plugin-transform-decorators
navigate to /<your project root>/node_modules/react-native/packager/react-packager/.babelrc
Add "transform-decorators" to this list:
{
"retainLines": true,
"compact": true,
"comments": false,
"plugins": [
"syntax-async-functions",
"syntax-class-properties",
"syntax-trailing-function-commas",
"transform-class-properties",
"transform-es2015-arrow-functions",
"transform-es2015-block-scoping",
"transform-es2015-classes",
"transform-es2015-computed-properties",
"transform-es2015-constants",
"transform-es2015-destructuring",
["transform-es2015-modules-commonjs", {"strict": false, "allowTopLevelThis": true}],
"transform-es2015-parameters",
"transform-es2015-shorthand-properties",
"transform-es2015-spread",
"transform-es2015-template-literals",
"transform-flow-strip-types",
"transform-object-assign",
"transform-object-rest-spread",
"transform-react-display-name",
"transform-react-jsx",
"transform-regenerator",
"transform-es2015-for-of",
-->"**transform-decorators**"<--
],
"sourceMaps": false
}

Related

Next.js: Jest encountered an unexpected token. Jest failed to parse a file. Crashing due to dot ( .{color: red} ) before a className in CSS files [duplicate]

I am trying to get my first Jest Test to pass with React and Babel.
I am getting the following error:
SyntaxError: /Users/manueldupont/test/avid-sibelius-publishing-viewer/src/components/TransportButton/TransportButton.less: Unexpected token
> 7 | #import '../variables.css';
| ^
My package.json config for jest look like this:
"babel": {
"presets": [
"es2015",
"react"
],
"plugins": [
"syntax-class-properties",
"transform-class-properties"
]
},
"jest": {
"moduleNameMapper": {
"^image![a-zA-Z0-9$_-]+$": "GlobalImageStub",
"^[./a-zA-Z0-9$_-]+\\.png$": "RelativeImageStub"
},
"testPathIgnorePatterns": [
"/node_modules/"
],
"collectCoverage": true,
"verbose": true,
"modulePathIgnorePatterns": [
"rpmbuild"
],
"unmockedModulePathPatterns": [
"<rootDir>/node_modules/react/",
"<rootDir>/node_modules/react-dom/",
"<rootDir>/node_modules/react-addons-test-utils/",
"<rootDir>/node_modules/fbjs",
"<rootDir>/node_modules/core-js"
]
},
So what am I missing?
moduleNameMapper is the setting that tells Jest how to interpret files with different extension. You need to tell it how to handle Less files.
Create a file like this in your project (you can use a different name or path if you’d like):
config/CSSStub.js
module.exports = {};
This stub is the module we will tell Jest to use instead of CSS or Less files. Then change moduleNameMapper setting and add this line to its object to use it:
'^.+\\.(css|less)$': '<rootDir>/config/CSSStub.js'
Now Jest will treat any CSS or Less file as a module exporting an empty object. You can do something else too—for example, if you use CSS Modules, you can use a Proxy so every import returns the imported property name.
Read more in this guide.
I solved this by using the moduleNameMapper key in the jest configurations in the package.json file
{
"jest":{
"moduleNameMapper":{
"\\.(css|less|sass|scss)$": "<rootDir>/__mocks__/styleMock.js",
"\\.(gif|ttf|eot|svg)$": "<rootDir>/__mocks__/fileMock.js"
}
}
}
After this you will need to create the two files as described below
__mocks__/styleMock.js
module.exports = {};
__mocks__/fileMock.js
module.exports = 'test-file-stub';
If you are using CSS Modules then it's better to mock a proxy to enable className lookups.
hence your configurations will change to:
{
"jest":{
"moduleNameMapper": {
"\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/__mocks__/fileMock.js",
"\\.(css|less|scss|sass)$": "identity-obj-proxy"
},
}
}
But you will need to install identity-obj-proxy package as a dev dependancy i.e.
yarn add identity-obj-proxy -D
For more information. You can refer to the jest docs
UPDATE who use create-react-app from feb 2018.
You cannot override the moduleNameMapper in package.json but in jest.config.js it works, unfortunately i havent found any docs about this why it does.
So my jest.config.js look like this:
module.exports = {
...,
"moduleNameMapper": {
"\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/__mocks__/fileMock.js",
"\\.(scss|sass|css)$": "identity-obj-proxy"
}
}
and it skips scss files and #import quite well.
Backing my answer i followed jest webpack
Similar situation, installing identity-object-proxy and adding it to my jest config for CSS is what worked for me.
//jest.config.js
module.exports = {
moduleNameMapper: {
"\\.(css|sass)$": "identity-obj-proxy",
},
};
The specific error I was seeing:
Jest encountered an unexpected token
/Users/foo/projects/crepl/components/atoms/button/styles.css:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){.button { }
^
SyntaxError: Unexpected token .
1 | import React from 'react';
> 2 | import styles from './styles.css';
If you're using ts-jest, none of the solutions above will work! You'll need to mock transform.
jest.config.js
module.exports = {
preset: 'ts-jest',
testEnvironment: 'jsdom',
roots: [
"<rootDir>/src"
],
transform: {
".(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/jest-config/file-mock.js",
'.(css|less)$': '<rootDir>/jest-config/style-mock.js'
},
};
file-mock.js
module.exports = {
process() {
return `module.exports = 'test-file-stub'`;
},
};
style-mock.js
module.exports = {
process() {
return 'module.exports = {};';
}
};
I found this working example if you want more details.
Solution of #import Unexpected token=:)
Install package:
npm i --save-dev identity-obj-proxy
Add in jest.config.js
module.exports = {
"moduleNameMapper": {
"\\.(css|less|scss)$": "identity-obj-proxy"
}
}
Update: Aug 2021
If you are using Next JS with TypeScript. Simply follow the examples repo.
Else you will be wasting days configuring the environment.
https://github.com/vercel/next.js/tree/canary/examples/with-jest
I added moduleNameMapper at the bottom of my package.json where I configured my jest just like this:
"jest": {
"verbose": true,
"moduleNameMapper": {
"\\.(scss|less)$": "<rootDir>/config/CSSStub.js"
}
}

Not able to work with peer dependency in react native

I have one react-native app in which I am using "json-schema-rules" library. Now I have also created one library which is getting used in my react-native app like this "file:../custom_library" in package.json.
Now to resolve the version conflict, I decided to use "json-schema-rules" as a peer dependency in my custom library. So, the package.json is like this
Package.json of my react-native app:
{
"dependencies": {
"json-rules-engine": "^2.3.0",
"custom_library": "file:../custom_library"
}
}
package.json of my custom_library:{
"peerDependencies": {
"json-schema-rules": "^2.3.0"
}
}
Now the problem is, whenever I am using metro bundler, I get an error
error: bundling failed: Error: Unable to resolve module json-rules-engine
json-rules-engine could not be found within the project.
This is the case when I am using it in peerDependencies, I do not get any error if I use this library in dependencies.
Please help.
You can try to add an alias for the module in your project's babel config.
This means that when your custom packages tries to import "json-rules-engine" it will get served the version from the main app.
First install 'babel-plugin-module-resolver' then configure the alias in "module-resolver"
babel.config.js
const config = {
presets: ["module:metro-react-native-babel-preset"],
plugins: [
[
"module-resolver",
{
root: ["./src"],
extensions: [".js", ".jsx", ".ios.js", ".android.js"],
alias: {
"json-rules-engine": require.resolve("json-rules-engine")
}
}
]
]
};
module.exports = config;

vuejs use babel plugin-proposal-class-properties

I have a class where I use some static properties like this:
class Entity {
static LIMIT = 10;
}
So, i can do:
Entity.LIMIT
In order to do that I'm using babel plugin-proposal-class-properties and in my .babelrc I have:
{
"presets": ["#babel/preset-env"],
"plugins": [
["#babel/plugin-proposal-class-properties", { "loose": true }]
]
}
I'm using jest and my test passes using that config. Now I need to use funcionality of Entity class inside a vuejs component. But I got the error:
Module parse failed: Unexpected token. You may need an appropriate loader to handle this file type
I also tried a babel config file in my project root: babel.config.js
module.exports = {
presets: ["#babel/preset-env"],
plugins: [
["#babel/plugin-proposal-class-properties", { "loose": true }]
]
};
But didn't work.
How can i configure vuejs, to make work this babel plugin?
I'm using vue2.6.11 and vue-cli 3
I got this exact same issue when trying to use "importabular" with vuejs (vuejs 2, vue-cli-3). Importabular uses class properties, after some research I found this babel plugins (plugin-proposal-class-properties), I installed it and added it in vue.config.js.
To finally make it work, I had to add "importabular" (or the nested path) in the transpileDependencies: option. Why that? Because, by default, Babel ignores whatever is in node_module, so you have to tell Babel to not ignore this specific folder.
So, if you want to use babel or some babel plugins with some node_module with vue you should modify the vue.config.js as follow :
module.exports = {
transpileDependencies: [
'path/in/node_module',
],
}
and change the babel.config.js as follow:
module.exports = {
"presets": [
"#vue/cli-plugin-babel/preset"
],
"plugins": [
["#babel/plugin-proposal-class-properties"],
]
}

error Failed to get dependency config. while installing fonts

I am trying to install fonts with
react-native link ./assets/fonts/ and with react-native link
both are giving the same error:
"error Failed to get dependency config."
I updated my package.json
"rnpm": {
"assets": [
"./assets/fonts/"
]
}
Please help
I have made sure the path to the font folder is correct and still same problem
re-install and re-link solves the problem in my case
What version of your react-native?
If it is> 0.60, it is recommended to create the react-native.config.js file with the configurations below:
module.exports = {
project: {
ios: {},
android: {}, // grouped into "project"
},
assets: [
'./assets/fonts/',
],
};
Link without specifying the package name and it should work
react-native link

How do I resolve import with absolute path?

What do I need to setup in brunch-config.js to be able to resolve absolute path from project's root folder? i.e
import { helper } from '/imports/utilities/helper'
The reason being is I have a legacy React app and it imports local files by using relative path. While I'm trying to use brunch, I need to figure out a way to setup brunch so that it understands the path without having to change the code.
I tried to use npm alias but not sure how it works
npm: {
aliases: {
'/imports': 'imports/**'
}
}
Found the solution with babel-plugin-module-resolver package.
Since all my codes are under /imports dir, in brunch-config.js I setup an alias based on their documentation:
plugins: {
babel: {
plugins: [
...,
["module-resolver", {
"root": ["./imports"],
"alias": {
"/imports": ([, path]) => `./imports${path}`,
}
}]
],
presets: [
...
],
}
},
That way, if I do import Screen from '/imports/components/screens' it will resolve the file under ./imports/components/screens
You can set the alias in .babelrc too but you might want to use regex instead.