Search code examples
javascriptreactjspugjsx

how to use pug templating engine with reactjs


I have did the following in order to integrate pug with a newly created reactjs application :

1. Create a fresh reactjs app using create-react-app

2. Then I followed the instruction from babel-plugin-transform-react-pug to install the plugin as mentioned in pugjs official site.

I used npm install --save-dev babel-plugin-transform-react-pug to install the above plugin. Then I've created a .babelrc file in my root directory and add the following in .babelrc file

{
  "plugins": [
    "transform-react-pug",
    "transform-react-jsx"
  ]
}

3. In my react app I've created an App component like the following :

import React from "react"

class App extends React.Component {
  render() {
    return pug`
      div
        h1 My Component
        p This is my component using pug.
    `;
  }
}

export default App;

But whenever I run the app usng npm start, I get the error message

./src/App.js Line 5: 'pug' is not defined no-undef


Solution

  • I was able to make it work.The actual documentation for integrating pug with react was not so helpful.But I finally figured out how to do this. This is what worked for me :

    1. Create a react app using : create-ract-app puginreact1

    2. after that npm start ( to check if everything is ok)

    3. You need to eject the create-react-app. so run npm run eject. There are other options, but I went with eject.

    4. Then npm start again in order to check if everything is ok.

    5. You need to include babel plugin so that react recognize pug. So run npm install --save-dev babel-plugin-transform-react-pug

    6. In package.json ( instead of creating .babelrc file in root directory ) include the following babel configuration. If you already have one just include the presets and plugins properties in the existing bable config in package.json

    "babel": { "presets": [ "react-app" ], //already included "plugins": [ "transform-react-pug", "transform-react-jsx" ] },

    1. If you run npm start now you may get the following error

    can not find module "babel-plugin-transform-react-jsx

    1. Above mentioned missing babel-plugin-transform-react-jsx plugin can be found here

    2. Install it : npm install --save-dev babel-plugin-transform-react-jsx

    3. After that, if you run the app, you will get the following error

    pug is undefined no-undef

    1. As reactjs by default use [eslint-plugin-react][3], do the following from eslint-plugin-react-pug documentation

    frist, npm install eslint --save-dev

    then, npm install eslint-plugin-react-pug --save-dev

    1. Then in package.json modify eslintConfig. ( you could also use .eslintrc in root directory )

      "eslintConfig": { "plugins": [ "react-pug"], "extends": [ "react-app", "plugin:react-pug/all" ] }

    2. Then npm start

    Now pug templateing should work with react js. At least it worked for me.