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.js
tries 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.
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();
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With