How to include scss compilation to css during CRA build - reactjs

I want to create npm package from my CRA app. Lets say I have some components where I include .scss file. When I build this app, I compile .tsx/ts components to JavaScript files with their definitions.
Compiled folder hierarchy structure may looks like this
components
=> BurgerMenu
=> BurgerMenu.d.ts
=> BurgerMenu.js
=> BurgerMenu.js.map
However compiled JavaScript files imports scss files require("./burgerMenu.scss"); instead of css file and css file is not compiled into specific folder.
Desired result is below
components
=> BurgerMenu
=> BurgerMenu.d.ts
=> BurgerMenu.js
=> BurgerMenu.js.map
=> BurgerMenu.css
How I can set sass compile during build and in every single component change import from scss to css?
Sample BurgerMenu component
import * as React from "react";
import "./burgerMenu.scss";
export const BurgerMenu = (props) => {
//removed for brevity
};
package.json
{
"name": "app",
"version": "0.1.0",
"private": false,
"main": "dist/js/index.js",
"module": "dist/esm/index.js",
"types": "dist/js/index.d.ts",
"publishConfig": {
"access": "public",
"tag": "prerelease"
},
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject",
"build:lib": "yarn build:babel && yarn build:types && node ./scripts/copyTS.js",
//TODO: node sass compile
"build:babel": "concurrently \"yarn build:babel:esm && yarn build:babel:umd\" \"yarn build:babel:cjs\"",
"build:babel:cjs": "cross-env BABEL_ENV=cjs babel --source-maps --extensions \".js,.ts,.tsx\" src --out-dir dist/js --presets=#babel/env",
"build:babel:esm": "cross-env BABEL_ENV=esm babel --source-maps --extensions \".js,.ts,.tsx\" src --out-dir dist/esm",
"build:babel:umd": "cross-env BABEL_ENV=umd babel --source-maps --extensions \".js\" dist/esm --out-dir dist/umd --plugins=transform-es2015-modules-umd",
"build:types": "tsc -p tsconfig.gen-dts.json",
"clean": "rimraf dist",
"develop": "yarn build:types && yarn build:babel:esm --skip-initial-build --watch --verbose",
},
}

node-sass npm package can be used to convert all the .scss files to .css files and the same can be used your modules for importing
Add this in your package.json
"scripts" : {
...
"build-css": "node-sass src/scss/ -o dist"
}
Here is a nice explanation of how node-sass can be used - How to compile or convert sass / scss to css with node-sass (no Ruby)?

Related

Framer motion error after install the package and import

I get this error after installing and importing framer-motion in the middle of my project
Can't import the named export 'Children' from non EcmaScript module (only default export is available)
I have tried to install after npx create-react-app and it works fine. This only happened if I install the package in the middle. This is my project
First, install the react-app-rewired NPM package as a dev dependency.
Then, in package.json, update the start, build, and test scripts to replace react-scripts with react-app-rewired:
"scripts": {
"start": "react-app-rewired start",
"build": "react-app-rewired build",
"test": "react-app-rewired test",
"eject": "react-scripts eject"
},
Finally, paste this into a file in the project root directory named config-overrides.js:
module.exports = function override(webpackConfig) {
webpackConfig.module.rules.push({
test: /\.mjs$/,
include: /node_modules/,
type: "javascript/auto"
});
return webpackConfig;
}
Now npm start / yarn start should work.

.less files not getting picked up by less-loader

I have created a react app using create-react-app and I am using less for css. My app builds correctly, but none of the less files are loaded in build/static folder
I am using customize-cra with react-app-rewired to add a loader for less files.
config-overrides.js file
const {
override,
addLessLoader
} = require('customize-cra');
const path = require('path');
module.exports = override(
addLessLoader({
paths: [path.resolve(__dirname, 'src/')],
javascriptEnabled: true,
sourceMap: true,
})
);
scripts in package.json
"scripts": {
"start": "react-app-rewired start",
"build": "react-app-rewired build",
"test": "react-app-rewired test --passWithNoTests",
"eject": "react-scripts eject",
"release": "CI=true react-app-rewired test --coverage && npm run build && npm run package && npm run posttest",
},
dependencies
"less": "^4.1.1",
"less-loader": "^8.0.0",
"react-scripts": "4.0.2",
"webpack": "4.44.2",
"customize-cra": "^1.0.0"
The error that I was getting was
Module build failed (from ./node_modules/less-loader/dist/cjs.js): TypeError: this.getOptions is not a function
Referred this post and lowered the version of less-loader to 5.0.0 and it started working

Error when importing JSX files from another package in monorepo with React

I created a simple project to study monorepo. The example consists of three React applications, where one consists of a lib of components with the Storybook and the other two will import the components of this package.
However I am not able to import a component from another package.
When I import a common function, no error occurs.
Github repository
Error message
../components/src/button/Button.js
SyntaxError: /home/thiago/Documentos/Dev/projects/learn-monorepo/packages/components/src/button/Button.js: Support for the experimental syntax 'jsx' isn't currently enabled (7:5):
5 | function Button({label, ...rest}) {
6 | return (
> 7 | <div>
| ^
8 | <button {...rest}>
9 | {label}
10 | </button>
Add #babel/preset-react (https://git.io/JfeDR) to the 'presets' section of your Babel config to enable transformation.
If you want to leave it as-is, add #babel/plugin-syntax-jsx (https://git.io/vb4yA) to the 'plugins' section to enable parsing.
Button component
function Button({label, ...rest}) {
return (
<div>
<button {...rest}>
{label}
</button>
</div>
);
}
export { Button };
App.js
import React from 'react';
import { Button } from '#project/components';
function App() {
return (
<div>
<h1>Hello World - App 01</h1>
<Button label="Button"/>
</div>
);
}
export default App;
Package.json
{
"name": "project",
"version": "1.0.0",
"main": "build/index.js",
"author": "thiago <thenrique2012#gmail.com>",
"license": "MIT",
"private": true,
"workspaces": {
"packages": ["packages/*"]
},
"babel": {
"presets": [
"#babel/preset-react"
],
"plugins": [
"#babel/plugin-syntax-jsx"
]
},
"scripts": {
"bootstrap": "lerna bootstrap",
"start:app-01": "lerna run --scope #project/app-01 start",
"start:app-02": "lerna run --scope #project/app-02 start",
"start:storybook": "lerna run --scope #project/components storybook",
"start:web": "yarn start:app-01 & yarn start:app-02 & yarn start:storybook"
},
"devDependencies": {
"#babel/plugin-syntax-jsx": "^7.12.1",
"#babel/preset-react": "^7.12.10",
"babel-loader": "8.1.0",
"lerna": "^3.22.1"
}
}
You get error because you have not transpiled your shared react components. There are some (not official) solutions for this with create-react-app. One of them is to use react-app-rewired and customize-cra. Instal lthem as dev-dependency and add a config-overrides.js file to the root of your create-react-app:
var path = require('path')
const { override, babelInclude } = require('customize-cra')
module.exports = function (config, env) {
return Object.assign(
config,
override(
babelInclude([
/* transpile (converting to es5) code in src/ and shared component library */
path.resolve('src'),
path.resolve('../components'),
])
)(config, env)
)
}
Then use react-app-rewired instead of react-scripts in your scripts for start and build of the project:
"scripts": {
"start": "react-app-rewired start",
"build-prod": "react-app-rewired build",
"build": "react-app-rewired build",
"test": "react-app-rewired test",
"eject": "react-scripts eject"
},

Can't import react component library into CRA

I created a react component library for a project to create a shareable component library across
multiple projects using the same theme and similar components.
I am importing it by npm link and importing as import { Button } from 'ph-shared'
It throws error
Here's the link to lib code if that can help
https://github.com/usmantahirr/react-lib
Found the fix. You have to install react-app-rewired and react-app-rewired-alias
here's the code snippit
const path = require('path');
const {alias} = require('react-app-rewire-alias')
Add a file config-overrides.js in root and put this.
// config-overrides.js
module.exports = function override(config) {
alias({
react: path.resolve('./node_modules/react'),
})(config)
return config;
};
Modify scripts your package.json as follows
"scripts": {
"start": "react-app-rewired start",
"build": "react-app-rewired build",
"test": "react-app-rewired test",
"eject": "react-app-rewired eject"
},

How can I add the CopyWebpackPlugin to create-react-app without ejecting?

I am building a react application and I want to copy all image files from the source destination to the build destination. I am following some tutorials and so far managed to use react-app-wired and the CopyWebpackPlugin
I am getting no errors and no files are being copied.
This is my config-overrides.js
const CopyWebpackPlugin = require('copy-webpack-plugin');
module.exports = function override(config, env) {
if (!config.plugins) {
config.plugins = [];
}
config.plugins.push(
new CopyWebpackPlugin(
[
{
from: 'src/images',
to: 'public/images'
}
])
);
return config;
};
This is my package.json
{
"name": "public",
"version": "0.1.0",
"private": true,
"dependencies": {
"axios": "^0.18.0",
"copy-webpack-plugin": "^4.5.2",
"css-loader": "^1.0.0",
"prop-types": "^15.6.2",
"react": "^16.4.2",
"react-app-rewired": "^1.5.2",
"react-axios": "^2.0.0",
"react-dom": "^16.4.2",
"react-router-dom": "^4.3.1",
"react-scripts": "1.1.4",
"react-slick": "^0.23.1",
"slick-carousel": "^1.8.1",
"typeface-montserrat": "0.0.54",
"webfontloader": "^1.6.28"
},
"scripts": {
"build-css": "node-sass-chokidar src/ -o src/",
"watch-css": "npm run build-css && node-sass-chokidar src/ -o src/ --watch --recursive",
"start-js": "react-app-rewired start",
"start": "npm-run-all -p watch-css start-js",
"build-js": "react-app-rewired build",
"build": "npm-run-all build-css build-js",
"test": "react-app-rewired test --env=jsdom",
"eject": "react-scripts eject"
},
"devDependencies": {
"npm-run-all": "^4.1.3",
"style-loader": "^0.22.1"
}
}
My folder structure is
src/images
src/images/file.jpg
src/images/slider/1.png
src/images/slider/2.png
public/images (empty) so far
Assuming you just want to move files from -/src/<somewhere> to ./<somewhereElse> at build time.
You could just add an extra step to your build script in package.json. The step below is completely in your control and does not mess with any create-react-app scripts or configuration.
For example, I used the ncp package, but if you want more granular control, you can also create your own "step" with ncp or even with raw node fs api.
Here is a way to replicate what I did:
Setup
npx create-react-app img-upload
cd img-upload/
yarn add --dev ncp
Test Data
create src/images/ folder structure and put in files
ls -R src/images/
src/images/:
badge.jpg folder1
src/images/folder1:
applause.gif blank.png
Package.json
I only edited the part: "build": "ncp './src/images' './public/images' && react-scripts build",
{
"name": "img-upload",
"version": "0.1.0",
"private": true,
"dependencies": {
"react": "^16.4.2",
"react-dom": "^16.4.2",
"react-scripts": "1.1.5"
},
"scripts": {
"start": "react-scripts start",
"build": "ncp './src/images' './public/images' && react-scripts build",
"test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject"
},
"devDependencies": {
"ncp": "^2.0.0"
}
}
Test:
Before running build:
ls public
favicon.ico index.html manifest.json
After running build: yarn build
ls public
favicon.ico images index.html manifest.json
ls -R public/images
public/images/:
badge.jpg folder1
public/images/folder1:
applause.gif blank.png
ls build
asset-manifest.json favicon.ico images index.html manifest.json service-worker.js static
ls -R build/images
build/images/:
badge.jpg folder1
build/images/folder1:
applause.gif blank.png
Suggestion
I am assuming you ultimately need these files in build directory. If so, you can just switch your build script.
"build": "react-scripts build && ncp './src/images' './build/images'",
That way you won't pollute your public folder, which you may want to keep in your source control.
It is definitely not recommended to modify the node_modules/react-scripts/config/webpack.config.dev.js file as this will break when this particular package is updated. Also most probably you would be having node_modules ignored in your version control system, meaning this config wont be shared across developers or backed up.
Although I haven't tried myself personally you could use something like this : https://github.com/timarney/react-app-rewired to override the Webpack config.
You can have a look at the tutorial here : https://medium.com/#timarney/but-i-dont-wanna-eject-3e3da5826e39
Mine worked like this:
const { override, addWebpackPlugin } = require('customize-cra');
module.exports = {
webpack: override(
addWebpackPlugin(
new CopyWebpackPlugin({
patterns: [
{ from: 'src/config', to: 'config' }
],
})
)
)
With that, I'm taking the contents of my config folder and creating an equal one in the build also called config.
I think the problem is because you are using webpack-dev-server together with copy-webpack-plugin. If that's true, the copy-webpack-plugin will copy files to virtual directory which webpack-dev-server works. So that, In this situation, you need to add one more plugin to make it happen
If you want webpack-dev-server to write files to the output directory
during development, you can force it with the
write-file-webpack-plugin.
import WriteFilePlugin from 'write-file-webpack-plugin';
webpack config:
config.plugins.push(
new CopyWebpackPlugin(
[
{
from: 'src/images',
to: 'public/images'
}
])
);
config.plugins.push(new WriteFilePlugin());
You can visit the official document for more information: https://webpack.js.org/plugins/copy-webpack-plugin/
Hope this works!

Resources