4

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.

baris1892
  • 981
  • 1
  • 16
  • 29
  • Did you run `yarn run encore dev --watch` see https://symfony.com/doc/current/frontend/encore/simple-example.html#configuring-encore-webpack if Yes, check that the app.js is created in web/js – Smaïne May 20 '18 at 07:59
  • I'm running only `encore dev --watch` which works fine, the `app.js` and `index.js` are generated under `public/build`. – baris1892 May 20 '18 at 08:12
  • The generated `index.js`contains the following code: https://pastebin.com/3P8PvDty . So the `app.js` was required successfully, however calling the `test()` method does not work. – baris1892 May 20 '18 at 08:18
  • I'm not a JS expert but could you try to change `let app` by `var app` please ? – Smaïne May 20 '18 at 08:34
  • That doesn't matter, it's translated to "plain" JavaScript as you can see in the pastebin posted above (`var appTest = ...`). – baris1892 May 20 '18 at 09:09
  • I think there is a problem with the variable scope https://stackoverflow.com/questions/762011/whats-the-difference-between-using-let-and-var-to-declare-a-variable-in-jav – Smaïne May 20 '18 at 09:15
  • Hmm, `var app = require("./app");` still does not work, same error message and the generated `index.js` is identical. – baris1892 May 20 '18 at 10:40

1 Answers1

7

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();
});
Iwan Wijaya
  • 2,077
  • 1
  • 16
  • 14