Victor
Victor

Reputation: 22198

Refactor RequireJS modules (AMD) to Webpack modules (CommonJS)

I need to refactor a bunch of files that have a call like this

define(['module1','module2','module3' etc...], function(a, b, c etc...) {

   //bunch of code

   return Something;

});

to

var a = require('module1');
var b = require('module2');
var c = require('module3');

//bunch of code

module.exports = Something;

Seems like a pretty simple task, 99% of the code follow this pattern, but I just can't use regex because I can't balance the brackets with it.

I already have the files traversal figured out, on a grunt task, I just need to transform the file and write it back.

grunt.registerTask('refactor', '', function() {
    //traverse all files   
    grunt.file.recurse('./src/js/views', function callback(abspath, rootdir, subdir, filename) {
        var c;
        //only care about .js files
        if(filename.match(/\.js$/)){
            console.log(subdir, filename);
            c = grunt.file.read(abspath); //read file

            //modify it
            c = c + "\n/* Comment appended! */";  

            grunt.file.write(abspath, c); //write it back
        }

    });

    grunt.log.write("DONE").ok();
});

This is a one time job, so I'm looking for a quick-n-dirty solution, I will have to check all files manually afterward anyway, I just want to save some time.

Upvotes: 0

Views: 197

Answers (1)

felixmosh
felixmosh

Reputation: 35573

Regex is not the tool for the job.

You should use some kind of js parser, and there are many of them. There is phrases that related to modifying code, code-mod & code-shift.

Take a look on that tool.

Upvotes: 1

Related Questions