Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony 4: Webpack Encore - call method in other JS file

I want to call within the index.js file a method from app.js. But I get the error app.test is not a function. Snippet from my webpack.config.js:

Encore
    .addEntry('app', './assets/js/app.js')
    .addEntry('index', './assets/js/index.js')
    .setOutputPath('public/build/')
    .createSharedEntry('vendor', [
       './assets/js/vendor/jquery-3.2.1.slim.min.js'
    ])
   .autoProvideVariables({
       $: 'jquery',
       jQuery: 'jquery',
       'window.jQuery': 'jquery'
   });

app.js contains only the test method:

function test() {
    return "test123";
}

and index.jstries to call this method:

let app = require("./app");

$(document).ready(function () {
    console.log(app); // empty object {}
    console.log(app.test());
});

What is wrong with this setup? Did I misunderstood the concept of webpack? I thought it is possible to require the needed modules and access them like in the example above.

like image 452
baris1892 Avatar asked Mar 07 '23 04:03

baris1892


1 Answers

First, your modules are related, so you should only use 1 js entry. Remove your app.js entry in webpack.config.js. Next in your app.js, export your function

function test() {
    return "test123";
}

module.exports = {
    test
};

In your index.js

let app = require("./app");

$(document).ready(function () {
    app.test()
});

Or an alternative approach using ESM modules:

app.js

export function test() {
    return "test123";
}

index.js

import { test } from './app';

$(document).ready(function () {
    test();
});
like image 159
Iwan Wijaya Avatar answered Mar 12 '23 05:03

Iwan Wijaya