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.
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.
How can i use #import to import my components in my scripts from other folders in my react project.
For example i have a folder structure like this
src
|
--- App.jsx
|
--- pages
| |___ home.jsx
|
|
--- components
|__ HomeComponent.jsx
How can i use in home.jsx
import HomeComponent from "#components/HomeComponent"
if i just try to use import HomeComponent from "#components/HomeComponent" like
this i get error module not found.
You can do a relative import from pages/home.jsx like this
import HomeComponent from "../components/HomeComponent"
Here ../ means you are going up one directory level and then into components directory
You can also perform absolute imports by setting up additional tools like babel or webpack. An absolute import would look like this when you have set src as your root directory
import HomeComponent from "components/HomeComponent"
If you are using create-react-app, this setup is easy to do as all the tooling is already handled by create-react-app
You can read about it here under the absolute imports section - https://create-react-app.dev/docs/importing-a-component/
babel-plugin-module-resolver
This plugin can simplify the require/import paths in your project. For example, instead of using complex relative paths like ../../../../utils/my-utils, you can write #utils/my-utils. It will allow you to work faster since you won't need to calculate how many levels of directory you have to go up before accessing the file.
// Use this:
import MyUtilFn from 'utils/MyUtilFn';
// Instead of that:
import MyUtilFn from '../../../../utils/MyUtilFn';
// And it also work with require calls
// Use this:
const MyUtilFn = require('utils/MyUtilFn');
// Instead of that:
const MyUtilFn = require('../../../../utils/MyUtilFn');
Install the plugin
npm install --save-dev babel-plugin-module-resolver
or
yarn add --dev babel-plugin-module-resolver
Specify the plugin in your .babelrc with the custom root or alias. Here's an example:
{
"plugins": [
["module-resolver", {
"root": ["./src"],
"alias": {
"test": "./test",
"underscore": "lodash"
}
}]
]
}
.babelrc.js version
Specify the plugin in your .babelrc.js file with the custom root or alias. Here's an example:
const plugins = [
[
require.resolve('babel-plugin-module-resolver'),
{
root: ["./src/"],
alias: {
"test": "./test"
}
}
]
];
Good example: https://gist.github.com/nodkz/41e189ff22325a27fe6a5ca81df2cb91
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.
JSX works perfectly in my Vue.JS project ... Unless I use typescript.
I create a Vue.JS project without typescript
vue create test
cd test
npm run serve
I replace HelloWorld.vue by
<script>
import Vue from 'vue';
export default Vue.extend({
name: 'HelloWorld',
render(){return (<p>JSX !</p>)},
});
</script>
And it's working perfectly
I make an other project, but with typescript, replace again HelloWorld.vue, I get an error
Module parse failed: Unexpected token (4:35)
You may need an appropriate loader to handle this file type.
| export default Vue.extend({
| name: 'HelloWorld',
> render: function (h) { return (<p>JSX !</p>); }
| });
|
I've tried every thin clue I've found on internet: I've tried writting HelloWorld.tsx instead, configuring babel or tsconfig, I've tried creating jsx.d.ts, installing more packages, ... Everytime I get exactly this error.
Could anybody give me the magic recipe for having a Vue.JS project with both JSX and typescript ?
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.