How to merge multiple functions in JavaScript using Babel

Viewed 172

I have many JavaScript modules that all of them export data and some other different functions. I want to merge all of these files into one file. Here are a few of them:

File1.js

export default {
    data() {
        return {
            f1: 'something 1'
        }
    },
    foo() {
        // do something 1
    }
}

File2.js

export default {
    data() {
        return {
            f2: 'something 2'
        }
    },
    bar() {
        // do something 2
    }
}

File3.js

export default {
    data() {
        return {
            f3: 'something 3'
        }
    },
    zoo() {
        // do something 3
    }
}

The expected result is like this:

Result.js

export default {
    data() {
        return {
            f1: 'something 1',
            f2: 'something 2',
            f3: 'something 3'
        }
    }, 
    foo() {
        // do something 1
    },
    bar() {
        // do something 2
    },
    zoo() {
        // do something 3
    }
}

I have seen a few articles that it could be more reliable if AST techniques are used. Here is a nice article: Manipulating AST with JavaScript

How can I do that with Babel?

1 Answers

Using Webpack (with Babel used a loader to transform your code before bundling), you'd be able to move any functionality in the data method into its own module (keeping in mind this may mean handling different uses of that method in one module export).

In the other files, you could import and reference the new utility function as needed.

Babel will transform the import statements into require() expressions, which will be used by Webpack to bundle these different modules for distribution. In that bundle, you'll see only one reference to the data module, even though you're importing it multiple times.

Related