Comment

React app to AEM SPA- Webpack

Avatar

Level 7

09-09-2021

Prerequisites

  1. Node 8.9.0 - https://nodejs.org/dist/latest-v8.x/
  2. Java 1.8 - https://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html
  3. Maven 3.5.2 - https://archive.apache.org/dist/maven/maven-3/3.5.2/binaries/
  4. AEM 6.4 with Service pack 2

 

  1.  Use the below cmd to create your project-   

     

    mvn -B archetype:generate -D archetypeGroupId=com.adobe.aem -D archetypeArtifactId=aem-project-archetype -D archetypeVersion=24 -D aemVersion=6.5.0 -D appTitle="My React SPA Site" -D appId="mysitereact" -D groupId="com.demomysite.react" -D frontendModule=react -D includeExamples=y -D includeDispatcherConfig=n

  2. Open terminal and navigate to react-app directory and execute “npm install --save-dev webpack webpack-cli” to install Webpack
  3. webpack.config.js file need to be created and paste the following code snippet----

    const path = require("path");

    module.exports = {

     entry: "./src",

     output: {

       filename: "App.js",

       path: path.resolve(__dirname, "dist")

     },

     module: {

       rules: [

         {

           test: /\.js$/,

           exclude: /(node_modules)/,

           use: {

             loader: "babel-loader",

             options: {

               presets: ["@babel/preset-react"]

             }

           },

           enforce: "post"

         },

         {

           test: /\.css$/,

           loader: "style-loader!css-loader"

         }

       ]

     }

    };

     

  4. In project root  add .babelrc file and paste the following configuration

    {

     "presets": [

       [

         "@babel/preset-react",

         {

           "pragma": "dom", // default pragma is React.createElement

           "pragmaFrag": "DomFrag", // default is React.Fragment

           "throwIfNamespace": false // defaults to true

         }

       ]

     ]

    }

  5. Find and open package.json and add the following under scripts

     

    "develop": "webpack --mode development"

    And add the following DevDependencies section

     

    "devDependencies": {

      "@babel/preset-react": "^7.0.0",

      "babel-loader": "^8.0.5",

       "webpack": "^4.28.3",

       "webpack-cli": "^3.3.0"

     }

  6.  

     Run “npm install” and “npm run develop” to build project.
  7. A folder named dist and App.js will be under it (if you don’t have any styles)
  8. Take the index.html from public folder of your react-app and place it in your web server’s doc root folder. Update the file to include <script src="App.js" type="text/JavaScript"></script> before body tag close
  9. You should see your React application work fine in browser without dev server