
When you create your project with create-react-app(CRA), the babel configuration exists as part of the react scripts. This means that all babel related controls are nested inside of your project's node_modules directory. For all intents and purposes, they are not editable, and ejecting is required. Your .babelrc file will not be used.
The easiest and fastest way to get started with PrismJS is to use a CDN. Though a CDN may be convinient, it is almost always impossible to use it when working with frameworks such as React.
How to use PrismJS for syntax highlighting in React
Use babel-plugin-prismjs
to configure the languages, themes, and plugins to bundle with Prism. Install as a development dependency from NPM.
You need to register the plugin in your Babel configuration. To achieve this, create a .babelrc file at the root folder of your project, the same directory where package.json file is, as shown below:
Include the languages, plugins, and themes your project needs in the configuration file.
After completing the setup described above, import Prism into your React component and invoke the highlightAll
method in the useEffect
hook.
When using Prism, you need to wrap inline code in the code
HTML tag, and depending on the language you are highlighting, apply the appropriate class to it. The class name should take the form lang-xxxx
or language-xxxx
for example lang-javascript or language-javascript.
Prism forces you to use semantic HTML when adding code to your markup. Therefore, you must wrap your code in pre
elements when highlighting blocks of code.
The example below is a React Component to demonstrate this:
Setting up a custom .babelrc file without ejecting a React App created using create react app
In order to get react build process to look at the .babelrc file there's a couple of more simple steps. We'll use customize-cra which allows us to make changes to the build config without ejecting. customize-cra depends on react-app-rewired so we need to install the two dependencies.
using yarn:
yarn add customize-cra react-app-rewired --dev
or using npm:
npm install --save-dev customize-cra react-app-rewired
What this does is customize-cra replaces react-scripts and allows us to modify the build process. In order to do this, we need to create a new file with a standard name config-overrides.js
at the root folder of your project, the same directory where package.json and .babelrc files are, and put the following code:
This will tell the build process to now use the .babelrc file but there's one final thing we need to do which is to replace create-react-app with react-app-rewired.
In the package.json file, change the scripts property value from:
to:
1 reaction
0 comments
Be the first one to share your thoughts