AEM Cloud Service - Adding Source Maps for Main File in AEM React SPA


Code in this post is a workaround to open the main js file during build (eg. ui.frontend\build\static\js\main.174a7c53.chunk.js) and adjust the source map location to point to the right file... 

eg. to change //# to //# sourceMappingURL=/apps/eaem-spa-extend-model-client/clientlibs/clientlib-react/resources/static/js/

Github Code


1) Modify the build command in your project ui.frontend\package.json to add node copy-main-map.js

"build""react-scripts build && clientlib && node copy-main-map.js",

2) Use latest node version in ui.frontend\pom.xml

                        <id>install node and npm</id>

3) Add the following code in ui.frontend\copy-main-map.js

//this is for chaning the sourceMappingURL in clientlib-react main file
const path = require('path');
const fs = require("fs-extra");
const readline = require('readline');

const PROJECT_FOLDER_NAME = "eaem-spa-extend-model-client"; //path.basename(path.join(__dirname, '..'));

const MAP_BUILD_DIR = path.join(__dirname, 'build', "static", "js");

const CLIENTLIB_REACT_JS_DIR = path.join(__dirname,'..', 'ui.apps','src','main','content', 
                            'jcr_root','apps', PROJECT_FOLDER_NAME ,'clientlibs', 'clientlib-react', "js");

    dereference: true,
    filter: (filePath) => {
        if (fs.lstatSync(filePath).isDirectory()) {
            return true;
        return path.basename(filePath).startsWith("main.") && path.basename(filePath).endsWith(".map");

const mainFile = path.join(CLIENTLIB_REACT_JS_DIR, fs.readdirSync(CLIENTLIB_REACT_JS_DIR).filter((fileName) => {
    return fileName.startsWith("main.")

const mainMapPath = "/apps/" + PROJECT_FOLDER_NAME + "/clientlibs/clientlib-react/resources/static/js/" + path.basename(mainFile) + ".map";

async function writeCorrectSourcePath() {
    const fileStream = fs.createReadStream(mainFile);

    const rl = readline.createInterface({
        input: fileStream,
        crlfDelay: Infinity
    let mainFileContent = "";

    for await (const line of rl) {
        if(line.startsWith("//# sourceMappingURL=")){
            mainFileContent = mainFileContent + "//# sourceMappingURL=" + mainMapPath + "\r\n";

        mainFileContent = mainFileContent + line + "\r\n";

    fs.writeFileSync(mainFile, mainFileContent, 'utf-8');


No comments:

Post a Comment