emulsify-ds / emulsify-drupal

Drupal theme built with Storybook and Webpack
GNU General Public License v2.0
92 stars 42 forks source link

Using Webpack to minify JS files makes it impossible to use Drupal.t() for translations #245

Open HeikkiYlipaavalniemi opened 2 years ago

HeikkiYlipaavalniemi commented 2 years ago

At the moment when I am using Webpack to minify the JS files it makes it impossible to use functions like Drupal.t() to translate strings with JS.

The problem being that Drupal is being replaced by for example r in the minified JS file which leads to the following error:

Uncaught ReferenceError: r is not defined
    attach dist/js/02-molecules/menus/main-menu/main-menu.js?v=1.0.2:1
    attachBehaviors core/misc/drupal.js?v=9.2.11:27
    attachBehaviors core/misc/drupal.js?v=9.2.11:24
    <anonymous> core/misc/drupal.init.js?v=9.2.11:29
    listener core/misc/drupal.init.js?v=9.2.11:17

There is also a drupal.org issue about a similar problem: https://www.drupal.org/project/drupal/issues/2893361

The suggested fix would be to add a following config to Webpack:

externals: {"drupal": "Drupal" },

I tested adding this to webpack.common.js under the exports but it didn't seem to have an effect when building the JS.

Has anyone else encountered this problem?

HeikkiYlipaavalniemi commented 2 years ago

We seem to been able to fix this by adding this to the webpack.common.js and refactoring our custom JS a bit to make sure that Drupal variable is passed along correctly.

externals: {
    'Drupal': 'Drupal',
  },