Skip to content

Importing / Exporting Dependencies

Functions/Class in files in Javascript can not be auto loaded like in PHP and need to be imported as required.

Dependencies need to be imported using the import statement before they can be used, depending on the libraries you want to consume there may be more specific things that need to be imported to get things working.

Be sure to refer to the package documentation for more specific instructions for your use case.

TL;DR

To make it possible to re-use a Javascript class or function - export the class/function in the file they are defined.

Class Example

MyClass.js

export default class MyClass {
    // logic goies here
    static doSomething() {
        return "Something";
    }
}

OtherClass.js

import MyClass from "MyClass.js";

export default class OtherClass {
    static doSomethingElse() {
        return MyClass.doSomething() + "else";
    }
}

Setting module directories

For imports to be resolved without having to input full absolute paths, you will need to add the directories to the module resolve config in Encore/Webpack

// Encore Example - place after the main Encore method chaining block
let config = Encore.getWebpackConfig();

// Set the source rou
config.resolve.modules = [
    path.resolve(__dirname, 'node_modules'),
    path.resolve(__dirname, 'assets/js')
];

module.exports = config;