As per Preact documentation, to convert a React app to Preact you have to alias webpack:
{
"resolve": {
"alias": {
"react": "preact-compat",
"react-dom": "preact-compat"
}
}
}
How can you do this with create-react-app since that hides webpack under react-scripts dependency?
Thank you!
I think the most elegant solution is to use customize-cra. This way you can avoid ejecting or maintaining a separate fork of create-react-app.
First, you need to install customize-cra:
yarn add customize-cra react-app-rewired --D
Then, go to package.json, change your scripts to the following (this step is crucial but is not explicitly mentioned in customize-cra's docs):
"scripts": {
"start": "react-app-rewired start",
"build": "react-app-rewired build",
"test": "react-app-rewired test",
"eject": "react-scripts eject"
},
Go to the root of your project, create a file called config-overrides.js with the following content (assuming you're using Preact X):
const { override, addWebpackAlias } = require('customize-cra');
module.exports = override(
addWebpackAlias({
'react': 'preact/compat',
'react-dom': 'preact/compat'
})
);
Run yarn start... And Voila!
There's Preact CLI which allows you to create preact apps without any module bundlers. It's the recommended tool to create starters for Preact apps.
npx preact-cli create default my-project
# Go into the generated project folder
cd my-project
# Start a development server
npm run dev
Watch out for templates which are using Preact 8.x. The newest version (as of 7/25/21) is Preact X (Preact version 10.x). The default template uses Preact X.
If you want to use create-react-app to make a Preact app, you can use this workaround (documented here):
npx create-react-app my-app --scripts-version #just-boris/preact-scripts
cd my-app
# The dependencies used by `create-react-app` are still pointing to
# react, so under root application folder it's required to run:
npm uninstall react react-dom
npm install preact
# `preact-compact` is bundled with `preact` under `preact/compact` in
# Preact X, but if you are using an older version run this:
# npm install preact-compact
This can also be done with yarn.
Preact official docs
Section on how to upgrade from Preact 8.x to Preact X
In my experience, the app created with the 2nd approach started seamlessly. However, I didn't try importing any complex/advanced React components.
I had issues porting such components into a Preact app created with preact-cli. I'll try again and provide more details if needed.
Alternatively, you can get it working with craco:
// craco.config.js
module.exports = {
webpack: {
alias: {
"react": "preact/compat",
"react-dom": "preact/compat"
}
}
}
Note: Do not uninstall react, #types/react, or #types/react-dom after adding preact!
react is still required by react-scripts to run craco start and friends.
#types/* are still required by your IDE for type suggestions.
Note: Bundle analyzers may still report that you're using React!
Make sure to double-check your output directory for real build sizes.
Related
I've been trying to get up a react and django application. First, I had followed this set of videos here: https://www.youtube.com/watch?v=6c2NqDyxppU&list=PLzMcBGfZo4-kCLWnGmK0jUBmGLaJxvi4j&index=3. There was a bunch of commands that you can see in the description that needed to be run in as well as a lot of copy pasting configuration files.
Later, my friend told me that create-react-app existed and would set up everything needed with just one command. I tried it, and it worked really well. However, there were issues with connecting it to django. The files that came out of create-react-app were different to the ones shown in the video and when I tried searching it up, a few solutions said to use npm run build and pass the build folder into django.
Running a build takes quite a long time and it is not automatic as it was when I had the webpack and babel system. What am I supposed to do to configure create-react-app so that I can get it to update automatically and get it into django.
Some places said that I could edit the config files when I do npm run eject. There is a problem that the package.json files in the tutorial project and the create-react-app project are not the same. The thing that lets the webpack and babel project update is this snippet of code in the package.json file:
"scripts": {
"dev": "webpack --mode development --watch",
"build": "webpack --mode production"
},
I ejected my create-react-app project but create-react-app doesn't use webpack so I won't be able to use this. What do I do?
I'm using craco and craco-alias to implement aliases for imports in my Create React App project.
Followed instructions in https://github.com/gsoft-inc/craco/blob/master/packages/craco/README.md#installation and https://github.com/risenforces/craco-alias#readme
I configured package.json to use craco instead of react-scripts for starting dev server, tests and production build
...
"scripts": {
"start": "craco start",
"build": "craco build",
"test": "craco test",
"lint:css": "stylelint './src/**/*.css'",
"lint:js": "eslint 'src/**/*.js'",
"test:w": "craco test --watch",
"postinstall": "patch-package"
},
...
Then I created jsconfig.json file w aliases paths
"compilerOptions": {
"baseUrl": "./src",
"paths": {
"#components": ["components/*", "components"],
"#constants": ["constants/*", "constants"],
"#assets": ["assets/*", "assets"],
"#store": ["store/*", "store"],
"#utils": ["utils/*", "utils"]
},
"include": ["src"],
"exclude": ["node_modules", "build", "coverage"]
}
And craco.config.js file, which uses craco-alias plugin
/* craco.config.js */
const CracoAlias = require('craco-alias');
module.exports = {
plugins: [
{
plugin: CracoAlias,
options: {
baseUrl: './src',
source: 'jsconfig',
}
}
]
}
Now I'm using aliases for imports in my app like this
// root index.js file
...
import Layout from '#components/Layout';
import store from '#store'; // this line causes error on CI build
function App() {
return (
<Layout>
/* inner components */
</Layout>
);
}
Everything works fine (aliased imports works on dev-server, in jest tests and even if I serve locally built project) until I push it to github repo. That repo has configured github actions to build and test project on remote server and it fails with error on build step, after installing all packages.
Run yarn build
yarn run v1.22.4
$ craco build
Creating an optimized production build...
Browserslist: caniuse-lite is outdated. Please run next command `npm update`
Failed to compile.
./src/index.js
Cannot find module: '#store'. Make sure this package is installed.
You can install this package by running: npm install #store.
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
##[error]Process completed with exit code 1.
Could somebody help me understand what wrong with my code? Why craco or webpack expect '#store' to be external package instead of aliased import of internal module?
In my case problem wasn't in craco or webpack, but in my previous actions and OS filesystem differences. I'm using Windows 10 and WSL in VS Code terminal. So before I use '#' symbol for aliases I tried to use CamelCase for my folders and renamed it via windows explorer (because for me it was simpler to close VSCode and rename files via explorer than to open new bash terminal in new VSCode window after closing opened files).
Then I prefer to use '#' symbol and rename folders back to lowercase. I configured aliases and pushed changes to remote github repo, where CI actions were run. When CI was running actions it can't find 'store' folder (because previously I renamed it to 'Store' and it was last saved path to folder in git), so it tried to find external package named 'store'.
To fix this I change git config to stop ignoring namecasing for my folder by running command git config core.ignorecase false. Git history was updated, I push it to remote repo and CI actions succeeded.
I've tried react-app-rewire-less module, but it doesn't work.
react-app-rewire-less-modules but it returns error after install
react-app-rewire-less works.
My problem was that I import "name.less" instead of "./name.less";
UPD
Also for them who are looking for solution - you can use craco
CRA has a documentation for integrating SASS in to it. You can pretty much change SASS tools there to LESS to achieve what you want.
Here's what I did:
I installed less and less-watch-compiler
yarn add less less-watch-compiler
Then add this line to scripts in package.json
"scripts": {
"watch-css": "less-watch-compiler src/ ./",
"start": "react-scripts start",
Now when running
yarn watch-css
When I make a change in src/App.less, corresponding src/App.css is generated.
I just started coding in React using create-react-app. In the documentation it's said
The page will reload if you make edits.
I don't know which module is responsible for auto reload (webpack or react-hot-reloader?) but it's not working. I edited file using different editors (Sublime, VIM, ..) but it seems problem is for something else. Any advice how to debug it?
After too many searches I found Webpack watch uses inotify to observe file changes and in ubuntu it's set to a low value. a quick fix:
sudo -i
echo 1048576 > /proc/sys/fs/inotify/max_user_watches
exit
If you want change it permanently (from Ronald answer):
echo "fs.inotify.max_user_watches=524288" >> /etc/sysctl.conf
sudo sysctl -p
You may also need to add a .env file in the root directory of your project with this line "FAST_REFRESH=false" as noted in create react app docs.
echo "FAST_REFRESH=false\n" | cat > .env
Year 2021
I had this issue in react ^17.0.2 I fixed it by adding a .env file and setting FAST_REFRESH=false.
Just create a .env file in the root directory of your project and add FAST_REFRESH=false in the file.
For Ubuntu users, run this in the terminal:
sudo gedit /etc/sysctl.conf
Scroll to the bottom and paste:
fs.inotify.max_user_watches=524288
Save and close the editor, then run this:
sudo sysctl -p
To check your success:
cat /proc/sys/fs/inotify/max_user_watches
This should return 524288
by apsrcreatix
Ref: https://github.com/flathub/com.visualstudio.code/issues/29#issuecomment-477126012
I had the same problem in Ubuntu.
The problem was resolved by deleting node_modules and then run
yarn install // or npm install
I hope to save someone else the same pain I experienced.
I'm using Windows 10 and Ubuntu 20.04 WSL, with nvm to manage node/npm.
I had to:
Use Node v16.14.2 in nvm (which also uses npm 8.5.0)
Change react-scripts from "react-scripts": "5.0.0" to "react-scripts": "4.0.3" in my package.json file
Change my package.json start script to
"start": "CHOKIDAR_USEPOLLING=true react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
I then ran npm install to update react scripts and restarted the bash terminal
I also followed Ronald Araújo's advice in his answer for good measure.
5 hours later, it's finally working!
Good luck everyone!
There actually is solution to get Fast refresh working.
Use this patch https://github.com/facebook/create-react-app/pull/11105/files
From #pmmmwh
Use https://www.npmjs.com/package/patch-package for editing your dependencies.
install patch-package (via npm or yarn into your project)
npm: npm i patch-package
yarn: yarn add patch-package postinstall-postinstall
Edit package.json and add postinstall script
"scripts": {
+ "postinstall": "patch-package"
}
Edit file YOUR_PROJECT/node_modules/react-dev-utils/webpackHotDevClient.js - with changes introduced in github pull request above
run npx patch-package react-dev-utils
commit changes created by this script (e.q. ./patches/react-dev-utils+11.0.4.patch)
run your app, now it will refresh on changes
Or wait for new release of react-dev-utils (it is not yet released, last version #11.0.3 doesn't contain this update).
My hot reload in Create React app broke due to updating some packages (probably because of typescript). I had to solve it without the ejecting of CRA.
I managed to fix it by upgrading to version 16.10 of these packages:
"react": "^16.10.0",
"react-dom": "^16.10.0"
And it worked just fine!
My code in index.tsx:
...
const isDev = process.env.NODE_ENV === 'development'
const rootEl = document.getElementById('root')
ReactDOM.render(<App />, rootEl)
if (isDev && module.hot) {
module.hot.accept('screens/App', () => {
ReactDOM.render(<App />, rootEl)
})
}
Hint:
First try just this code (maybe you are setting wrong path)
if (module.hot) {
module.hot.accept()
}
If this start working then you want to specify the path in order to make hot loading more effective (less bubbling = shorter loading)
Try adding CHOKIDAR_USEPOLLING=true in a .env file.
If the React webpage is not reloading upon saving changes, try adding this line to the App.js file:
import React from 'react';
After create-react-app,I change my project's name.This is one of reasons which make reload not working.Then I create-react-app again,reload is working now.
I'm just starting the react.js tutorial, I've downloaded the files and then it mentions:
"Follow your progress by opening http://localhost:3000 in your browser (after starting the server). "
I know this may sound stupid, (bear with me since I'm a beginner with React) but how do I start the server in this instance?
Thanks.
Marc
Pretty solid chance it's npm start from the project root.
Properly packaged modules will have some node scripts configured in package.json. It's customary to use start as the script to run the dev environment, though some might use build, dev, or other names.
Here's official installation process: link, and officially recommended tutorials
# install react cli
npm install -g create-react-app
# create app
create-react-app my-react-app-name
# go to project folder
cd my-react-app-name
# install dependencies
npm install
# start live server
npm start
output:
$ You can now view my-react-app-name in the browser.
$ Local: http://localhost:3000/
$ On Your Network: http://192.168.0.105:3000/
$ Note that the development build is not optimized.
$ To create a production build, use npm build.
You can run any one of the below mentioned commands to start the node server for your ReactJS application:
npm run-script start
npm run start
npm start
All the above commands are equivalent but people prefer the third one as it is the shortest to type on keyboard.
The start parameter in these commands maps to the start key present under scripts configuration present in package.json file of any ReactJS application. Here is a sample package.json file of my hello-world application:
{
"name": "hello-world",
"version": "0.1.0",
"private": true,
"dependencies": {
"react": "^15.4.2",
"react-dom": "^15.4.2"
},
"devDependencies": {
"react-scripts": "0.9.5"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject"
}
}
You can see that react-scripts start is written in front of start key. So react-scripts start command will get fired when we run any of the three commands which I had enlisted in the beginning e.g. npm start.
I used Node to run the server. The steps I followed are:
I downloaded the zip package from the Running a server section
here
I had the link open: http://localhost:3000/
I opened up Node.js Command Prompt and navigated to the downloaded
zip project. From Node example here:
Just type the commands in the example:
First npm install and then
node server.js.
See the screen shot below:
When I refresh the localhost web page I see the following:
Sounds like you're following the official React tutorial, in which case the instructions to start the various included server implementations are here.