'How to add all page specific entries from dependency

I'm currently upgrading an existing app with legacy per-page frontend javascript and CSS to Symfony's Webpack Encore. The app and it's dependencies each supply their own page-specific JavaScript or CSS in a webpack.config.js. For example:

MyApp

// webpack.config.js
  Encore
      // ...
      .addEntry('app', './assets/app.js')
      .addEntry('checkout', './assets/checkout.js')
      .addEntry('account', './assets/account.js')
      // ...

TheDependencies

// webpack.config.js
  Encore
      // ...
      .addEntry('login', './assets/login')
      .addEntry('logout', './assets/logout')
      // ...

Naturally the easy solution is to manually copy the dependencies entries into MyApp :

// webpack.config.js
  Encore
      // ...
      .addEntry('app', './assets/app.js')
      .addEntry('checkout', './assets/checkout.js')
      .addEntry('account', './assets/account.js')
      .addEntry('login', './node_modules/my-dependency/assets/login')
      .addEntry('logout', './node_modules/my-dependency/assets/logout')
      // ...

However, this pose problems (1) in the event the dependency is updated with new entries or (2) when multiple dependencies (~5) each supply multiple (10+) entries.

I want to find a way to easily import every page-specific entries from each dependencies. For example, something similar to this pseudo-code:

// webpack.config.js
  Encore
      // ...
      .addEntry('app', './assets/app.js')
      .addEntry('checkout', './assets/checkout.js')
      .addEntry('account', './assets/account.js')
      .addEntries('./node_modules/my-dependency/webpack.config.js')
      // ...

Is that possible and how could I achieve this ?



Solution 1:[1]

I propose an answer that is not directly related to webpack. Even though you're maybe not using a JS framework, since 2015 (ES6), JavaScript has had the ES6 modules standard to import modules in Node.js, also supported by most browsers.

for example for your account (I assume it contains your login and logout in this example) and this is just a

Using package.json:

{
    "type": "module" }

With this, your source code should use import syntax

Then login.js (all your script here I put a function example) :

  export function login() {
      return "you're logged in";
    }

Then account.js

import { login } from './login.js';
let val = login();  val is "logged";

You can then just import your script account.js like you did in your webpack. In the end, you can add few entries in your webpack config, depending on which scripts are loading in each script with the import call, but in a way it allows to organize them.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Lou