Reputation: 97
I need my react project build version to have hashed class names in in html and css. For example if I have:
<div className="test"></div>
I need to be build like this:
<div class="*hashcode*"></div>
can this be achieved in React?
Upvotes: 1
Views: 2719
Reputation: 338
If you use webpack
to build the scaffold from scratch, please continue to read(I assume you had set other configurations done).
Here are the steps
1 set the webpack config file
module.exports = {
...
module: {
rules: [
{
test: /\.(scss)$/i,
exclude: /node_modules/,
use: [
"style-loader",
{
loader: "css-loader",
options: {
modules: {
exportLocalsConvention: "camelCaseOnly",
localIdentName: "[name]__[local]--[hash:base64:5]",
},
},
},
"sass-loader",
],
},
...
}
2 create a scss file
// App.scss
.hello {
color: red;
}
3 Import the scss file and use it.
// App.jsx
import Style from './App.scss';
const App = () => {
return <div className={Style.hello}>Hello World!</div>
}
Then you should figure it out.
Since you want to add hash to className, you must handle the CSS flow.
It would help if you had the tool css-loader
. The option localIdentName
in modules
allows to configure the generated local ident name.
For more info check css-loader
Upvotes: 0
Reputation: 20451
You need CSS modules.
Create a file named [componentName].module.css
with your component. Let us say it looks like:
.divClass {
background-color : red;
}
Import it like a JS object:
import styles from './random.module.css`;
And use it here:
<div className={styles.divClass}></div>
Upvotes: 1