I am kind of new to Javascript programming. I tried writing a test for a script with JSX format, but somewhat it fails with Unexpected token.
Here's the test code, I haven't write any test yet.
//Rectangle.js
let assert = require('chai').assert,
path = require('path');
import Rectangle from './Rectangle';
And here's the code that needs to be tested
//Rectangle.jsx
import React from 'react';
class Rectangle extends React.Component {
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}
Here's the error
SyntaxError: Rectangle.jsx: Unexpected token (5:11)
3 | class Rectangle extends React.Component {
4 | render() {
> 5 | return <h1>Hello, {this.props.name}</h1>;
| ^
6 | }
7 | }
Here's the mocha command that I got from some articles nyc mocha --compilers js:babel-core/register Rectangle.js.
I also uploaded the code on github (link), so you could see the installed dependencies.
How should I fix this? Is there a step that I missed?
You need to add react preset to you babel config inside package.json
"babel": {
"presets": ["es2015", "react"]
}
I think you may need custom compiler to help you compile jsx code.
You can see the example here: Mocha-react repo.
Related
I'm working on a project in React using CSS modules for stylings.
I would like to test a component using Jest and React Testing Library, but when I try to render it I get this error:
Test suite failed to run
cssModule has no keys
3 | export default (style: {[key: string]: string}):any => {
4 | block.setSettings({throwOnError: true, modifierDelimiter: '--'});
> 5 | return block(style);
| ^
6 | };
7 |
block is an override from a function exported by the library bem-css-modules which I use for keeping BEM nomenclature while implementing css-modules.
I have managed to log the exact style (imported by the .module.scss file) which is passed to this function, and I have found that it is actually empty when rendering the component with react-testing-library:
import React from 'react';
import MyIcon from 'shared/components/myIcon/myIcon.component';
import styles from './myButton.module.scss';
import block from 'utils/bemCssModulesConfig';
console.log('styles', styles) // this logs "styles, {}" so it's empty object
const bem = block(styles);
This is the moduleNameMapper I am currently using:
"moduleNameMapper": {
"^.+\\.(scss|sass|css|less)$": "identity-obj-proxy"
}
I have already tryed using custom proxies copied from the internet or using external libraries as moduleNameMappers.
I have a parent repository developed with React, and I have a child Sub Module inside of it(which is developed by react too):
The project folder structure is something like below:
parent
/.git
/nodemodule
/src
/subModules/childProject
/.git
/src
/js
/x.jsx // i want this file from parent project
/...
/...
I want to access and use the x.jsx component from parent project. I imported it like blow in my parent project:
import X from '../subModules/childProject/src/js/x.jsx'
but it gives me unexpected token!
7 | return (
> 8 | <article className="center">
| ^
9 | this is test global component with in child Project
10 | </article>
11 | )
it looks like that it cannot transform it because I wrote just a test function in old JavaScript way like:
export default function test(x) {
return x * 2
}
It imported without any error and works but when I wrote function in arrow style like below:
export default function test(x) => x * 2
it does not work. It seems like it's just a runtime error of transpiling modules, how can I transpile and import react components from child submodule in to parent repository?
The problem was that Babel does not know that there is a submodule project in the root of the project, just by changing my .babelrc file to babel.config.js and configuring it by babelrcRoots I would be able to solve the issue:
Now my babel.config.js file looks like this:
module.exports = {
"presets": [
"#babel/preset-react",
"#babel/preset-env"
],
"plugins": [
"#babel/plugin-proposal-class-properties",
"#babel/plugin-proposal-object-rest-spread"
],
"babelrcRoots": [ "./", "./subModules/someFolder" ]
}
Now I can import any react component and JS modules from sub-repository in side my parent project and it works correctly.
This is what the react-hot-loader DOCs says:
https://www.npmjs.com/package/react-hot-loader
Note: You can safely install react-hot-loader as a regular dependency instead of a dev dependency as it automatically ensures it is not executed in production and the footprint is minimal.
Even though it says that. My goals are:
I want to remove react-hot-loader from my production bundle.
And I also want a single App.js file. That should work for DEV and PROD.
The only command that I have related to react-hot-loader is inside of my App.js file:
App.js
import { hot } from 'react-hot-loader/root';
import React from 'react';
import Layout from './Layout/Layout';
function App() {
console.log('Rendering App...');
return(
<Layout/>
);
}
export default process.env = hot(App);
If I run it just like this, I end up with the following line on my app.js transpiled and bundled file:
/* WEBPACK VAR INJECTION /(function(process) {/ harmony import / var react_hot_loader_root__WEBPACK_IMPORTED_MODULE_0__ = webpack_require(/! react-hot-loader/root */ "wSuE");
That's expected.
But if I change my App.js file to:
AppV2.js
import { hot } from 'react-hot-loader/root'; // KEEPING THE IMPORT
import React from 'react';
import Layout from './Layout/Layout';
function App() {
console.log('Rendering App...');
console.log(window);
return(
<Layout/>
);
}
// export default hot(App); <--- COMMENTED OUT THE hot() LINE
export default App;
And I add this line to my webpack.config.js
webpack.config.js
plugins:[
new webpack.IgnorePlugin(/react-hot-loader/)
]
I'll end up with a new transpiled app.js file with this line:
*** !(function webpackMissingModule() { var e = new Error("Cannot find module 'react-hot-loader/root'"); e.code = 'MODULE_NOT_FOUND'; throw e; }());
Note: The first '***' chars in the line above don't really exist. I had to add them in order to the ! exclation mark to be shown in the quote. Don't know why but you can't start a quote with an exclamation mark.
QUESTION
Isn't the IgnorePlugin supposed to completely ignore the react-hot-loader package? Why is it being marked as missing? See that it's not even being used on the code (since I've commented out the hot() call).
Ignore Plugin only excludes that particular module in bundle generation. However it will not remove the references to the module from your source code. Hence your webpack output is throwing that error.
One way of bypassing this error is to use the DefinePlugin to create a dummy stub for react-hot-loader. More on that here.
That said react-hot-loader itself proxies the children without any changes if the NODE_ENV is production. Check here and here. So in production mode apart from the hot() function call which directly returns your component, there is no other stuff that happens.
Another option could be:
// App.js
export default function AppFactory() {
if (process.env.NODE_ENV === "development") {
return hot(App);
} else {
return App;
}
}
// index.js:
import AppFactory from './App';
const App = AppFactory();
// ...
<App />
Now since webpack is creating bundles at build time, it knows if the mode is development or production (more on build modes) and should be able to eliminate the dead code with tree shaking and UglifyjsWebpackPlugin.
Make sure that if you are using Babel it's not transpiling your code to CommonJS - see Conclusion section, point 2 of the tree shaking page.
Pass the ambient mode to babel.
"scripts": {
"build-dev": "webpack --node-env development",
"build-prod": "webpack --node-env production",
},
I am trying to develop a react component that could be shared across different applications. The idea is any app could drop in the component, pass in some props, and get the same functionality everywhere. So apps can add my component as a dependency in package.json which will be downloaded in node_modules. Basically go from doing this
import testComponent from "./Components";
to this
import testComponent from "my-custom-components";
I tried doing npm install [githun-url-link] which seemingly worked fine. But after launching the app I get the error:
Failed to Compile
./node_modules/.../src/components/testComponent.js
SyntaxError: /Users/mzq/Workspace/.../testing/node_modules/.../src/components/testComponent.js: Support for the experimental syntax 'classProperties' isn't currently enabled (7:9):
5 |
6 | class testComponent extends Component {
> 7 | state = {
| ^
8 | currentPageIndex: 0,
9 | currentPageLabel: this.props.currentPageLabel,
10 | page: this.props.pages[0],
Add #babel/plugin-proposal-class-properties (https://git.io/vb4SL) to the 'plugins' section of your Babel config to enable transformation.
One solution I tried after a bit of Googling is
1) yarn add #babel/plugin-proposal-class-properties --dev
2) creating a babel.config.js in the root folder with following config
module.exports = {
presets: [
'#babel/preset-env',
'#babel/preset-react',
'#babel/preset-typescript'
],
plugins: [
'#babel/plugin-proposal-class-properties'
]
};
To no avail.
Enabled transform-class-properties plugin webpack module exports, which is helping me to have class which is a registered word in javascript to be used normally in my html code and transpilation step using the plugin takes on the heavy lifting.
I'm using enzyme for testing components now I have issue where in I have my component like this.
export default class Settings extends React.Component {
render() {
return (
<div class='something'>Settings</div>
);
}
}
If I want to test in my unit test if I have any something class in my Component it fails always.
export default class Settings extends React.Component {
render() {
return (
<div className='something'>Settings</div>
);
}
}
But if I do the above transformation myself, I have UT passing.
How can I do the transformation step to kick in before unit testing too. I'm using npm script test like this
"test": "mocha -w ./test/**/*.js --compilers js:babel-core/register --reporter spec",
My bad -- The solution lies in .bablerc solved it using another stackoverflow thread Mocha throws unexpected token error for ES6 object spread operator