I want to add a babel plugin inside create-react-app - reactjs

I want to add the following babel configuration in react-scripts I don't want to eject from cra I want to keep using it without ejecting. I see there is a way to fork the repo and add your custom configuration. But I want to know where exactly I can paste this.
// .babelrc or babel-loader option
{
"plugins": [
["import", { "libraryName": "antd", "libraryDirectory": "es", "style": "css" }] // `style: true` for less
]
}

There is, in theory, customize-cra, which lets you do things like override Babel plugins.
Here is a list of things you can do.
It doesn't appear to be maintained at time of writing, and for me didn't seem usable if your project is modules-based (ie import) as opposed to require.
CRA itself recommends forking their scripts as an alternative to ejecting, which is a pretty bold statement.

If you wish to override a property of one of the config files of React, you can just create that config file in your project's main directory and just set that single property, this will override that property in React's configuration. For babel you can just add it as a property in package.json like so:
"babel": {
"presets": [ ... ],
"plugins": [ ... ],
}
If you run npm run-script eject you are going to get a copy of all the config that ReactJS uses for your project in the main directory of your project/config, from there you can edit whatever you like, keep version tracking of your changes and not mess with the react repository.
If you insist on forking it you can fork the main create-react-app repository from here, which contains the react-scripts here

Related

Storybook webpack config not working - trying to run Storybook out of separate local project than components

I have a mature CRA-based React app running with Webpack 5. I would like to have a separate project (in git, etc) where Storybook lives and points to the components in the app. (The app has tons of devs in and out of it, and dropping a bunch of Storybook packages in there, as well as introducing legacy-peer-dependencies thanks to webpack 5, would be quite frowned upon).
I also want devs to have a good experience being able to use Storybook to write components, so I want Storybook to see the current code of the project components, not some exported package. And same as above, there are many devs and a lot of inertia, so moving components to a separate standalone library is not an option.
My ideal for local development:
components and stories: /MyProject-App/src/Components/...
storybook app. : /MyProject-Storybook/stories/...
(Production I'm not worried about yet)
Installing Storybook inside the app works fine (as long as you run with --legacy-peer-deps). I am using the npx storybook init script and it works fine. But if I try to run Storybook out of a separate directory and target the app directory's Components, it breaks. If I run Storybook out of the app, and point it to stories/components outside that repo (which I copied and pasted just as a debugging measure), it breaks. Going up and out of the current project root breaks.
To do this, I am trying to point stories in /MyProject-Storybook/.storybook/main.js to ../../MyProject-App/src/Components.... When I do this and npm run storybook, I get the error output:
File was processed with these loaders:
* ./node_modules/#pmmmwh/react-refresh-webpack-plugin/loader/index.js
* ./node_modules/#storybook/source-loader/dist/cjs/index.js
**You may need an additional loader to handle the result of these loaders.**
The error is always on some basic ES6 syntax, arrow functions etc. If I run the same Storybook install out of MyProject-App (same version numbers / same main.js just pointed at the local path instead of the ../other path) it works.
In addition to this, I tried it the other way - running storybook out of the App folder (where I know it runs), and only changing the main.js stories directory to an outside-that-repo folder where I copied my Components and stories into. It breaks in the same way - I get the same You may need an additional loader to handle the result of these loaders. message, with it pointing to any example of ES6 syntax as an 'error'.
I found this similar question - Storybook can't process TS files outside of the project
recommending to look into Storybook's webpack loaders - https://storybook.js.org/docs/react/builders/webpack
So I updated my .storybook/main.js to be the following:
module.exports = {
stories: [
'../../MyProject-Storybook/src/**/*.stories.mdx',
'../../MyProject-Storybook/src/**/*.stories.#(js|jsx|ts|tsx)'
],
addons: [
'#storybook/addon-links',
'#storybook/addon-essentials',
'#storybook/addon-interactions',
'#storybook/preset-create-react-app'
],
framework: '#storybook/react',
core: {
builder: '#storybook/builder-webpack5'
},
webpackFinal: async (config, { configType }) => {
config.module.rules.push({
test: /\.(js|jsx)$/,
use: [
{
loader: require.resolve('babel-loader'),
options: {
reportFiles: ['../**/src/**/*.{js,jsx}', '../../MyProject-Storybook/**.stories.{js,jsx}']
}
}
]
});
config.resolve.extensions.push('.js', 'jsx');
return config;
}
};
but to no avail - output from npm run storybook remains unchanged, an excerpt:
File was processed with these loaders:
* ./node_modules/#pmmmwh/react-refresh-webpack-plugin/loader/index.js
* ./node_modules/#storybook/source-loader/dist/cjs/index.js
You may need an additional loader to handle the result of these loaders.
| backgroundColor: { control: 'color' },
| },
> } as ComponentMeta<typeof Button>;
|

How to make a path alias in CRA TypeScript in 2022?

I just initiated CRA npx create-react-app my-app --template typescript and I want to make an alias when calling components, like:
import components from '#components'
where the components is located at src/components.
I've tried to config in tsconfig.json by adding:
{
"compilerOptions": {
...
"baseUrl": "./src",
"paths": {
"#utils/": ["./utils/"],
"#utils/*": ["./utils/*"]
}
}
}
Also in webpack.config.js by adding:
// const TsconfigPathsPlugin = require('tsconfig-paths-webpack-plugin')
const path = require('path')
module.exports = {
resolve: {
// plugins: [new TsconfigPathsPlugin()],
alias: {
'#utils': path.resolve(__dirname, './src/utils/'),
'#utils/*': path.resolve(__dirname, './src/utils/*')
}
}
}
But it's still doesn't work.
Anyone could help me to solving these problem? But, I don't wont to use other libraries like #craco/craco.
The issue is that CRA uses its own Webpack config under the hood. Simply making a new webpack.config file doesn't actually point CRA to it, unless you run npm run eject.
Doing so is irreversible, but will add the config files to your project. From there, you should be able to modify your build settings to fit your needs.
Reminder that this cannot be undone in your project, barring perhaps a git reset, and may be more than you bargained for.
This issue with aliases seems to be a known one. Something people deemed possible earlier seems to no longer be working, or supported. Some people are speculating this could have something to do with the recent update of Webpack to version 5. And while some people claim that craco doesn't work for them, I was able to get it to work in a brand new CRA app with minimal changes. I know you're not interested in that so I won't post it here.
Alternatively, CRA allows the use of absolute imports via the src baseUrl. This will point both VSCode and Webpack to your final files, but you won't be able to set up custom paths.
"baseUrl" : "."
Using multiple index.ts files and exporting nested code up to the highest level in the directory, I'm able to keep the import paths as short as an alias:
import { persistor, store } from "src/state-management";
This could be good enough for you. If not, consider adding a package to override some of CRA's Webpack settings, or ejecting and taking matters into your own hands.

Why does create next app install with postcss errors

The code in question is very simple. I have an "app" folder with a server directory inside. I open a terminal. I cd into app. I then type npx create-next-app client. next installs. I change directory to app/client. I run npm run dev.
I get this in console...
Error: Your custom PostCSS configuration must export a plugins key.
I tried with earlier version of create-next-app. Same. Tried with other installation on my machine. Same.
Is there any way to find out what postcss next thinks is being used?
Can i add a config to fix it?
Okay, I found the answer! I added a practically empty postcss.config.json.
{
"plugins": [
]
}
First, I tried using the exact example, "default", from the nextjs docs...
{
"plugins": [
"postcss-flexbugs-fixes",
[
"postcss-preset-env",
{
"autoprefixer": {
"flexbox": "no-2009"
},
"stage": 3,
"features": {
"custom-properties": false
}
}
]
]
}
That didn't work. Then I erased the json data leaving just an empty plugins array. Worked.
But why...

Can I have multiple babel.config.js in a monorepo?

I have a monorepo with the structure like below
babel.config.js
packages/
|---mobile/
|----package.json
|----src/index.js
|---desktop/
|----package.json
|----src/index.js
|---server/
|----package.json
|----src/index.js
So my babel configuration for mobile and desktop packages are same, whereas configuration for serverpackage is different.
Now, how can I have that configuration done? One solution, that I can think of is that to have a babel.config.js at the root of monorepo which would have configurations for mobile and desktop packages and a separate configuration for server package in a babel.config.js at server package level. I am not sure, can we even have multiple babel.config.js.
Yes, you can achieve what you asked by having multiple config files. It is mentioned as File-relative configuration in babel documentation.
Create a .babelrc or .babelrc.js file in each of your directories (mobile, desktop, server)
For more details look at https://babeljs.io/docs/en/next/config-files
Personally, I think using separate files would lead to confusion. Assuming you've set up your system in a way that works already and you're just asking how to specify different configs for different locations, you can use the "overrides" option. For example, your config can do
module.exports = {
overrides: [{
test: [
'./desktop',
'./mobile',
],
// put all your normal babel options for these folders here
}, {
test: [
'./server',
],
// put all your normal babel options for the server here
}],
};

Next.js can not load JSX files via custom .babelrc configuartion

I am trying to use the .jsx file type and have created a custom .babelrc file as per the Next.js documentation (see below). https://github.com/zeit/next.js#customizing-babel-config
{
"plugins": [
["transform-react-jsx", {
"extensions": [".jsx"]
}]
],
"presets": [
"next/babel"
]
}
However with the above .babelrc file I receive the following error:
Can someone point me in the direction as to what I am doing wrong to get jsx files to load properly?
Cheers,
Stefan
Next.js has support for .jsx files out of the box. There should be no need to customize your .babelrc, so you can either use the default one or just delete it altogether.
Make sure you are running the latest version of Next.js, and possibly delete the node_modules and the .next folder in your project directory. Then install the dependencies again & build.

Resources