1

I have a JavaScript Framework based on Webpack. There I want to import (or not) an arbitrary module (JavaScript file with a custom function exported as default) by a custom condition made in the Webpack configuration:

// in webpack.customSettings.js
module.exports = {
  const customJsFilePath = 'path/to/custom/js/file';
  // alternatively, if no import is desired:
  // const customJsFilePath = null;
};

// in webpack.config.js
const settings = require('./webpack.customSettings.js');
// ...
new webpack.DefinePlugin({
  'process.env': {
    PATH: JSON.stringify(settings.customJsFilePath || ''),
  },
});

This determines if and which custom module is required during the Webpack build process. So a dynamic import like the following seems to be unnecessary and not really efficient, because the path is already fixed at runtime and I don't want to load dynamically an extra file (chunk) during runtime in this case:

// somewhere in my main index.js
if (process.env.PATH) {
  import(`${process.env.PATH}/index.js`).then((module) => {
    const myFunc = module.default;
    // ...
  });
}

I would rather have the custom file included directly in my bundle by Webpack. Something like that:

// somewhere in my main index.js
const myFunc = awesomeGlobal.customFunc;
if (myFunc) {
  // ...
}

I know that the following doesn't work, unfortunately:

// in my main index.js
import customFunc from `${process.env.PATH}/index.js`;

But what can I do? Perhaps something in Webpack?

1 Answer 1

1

Ok, I came up with the solution myself. I use the Webpack ProvidePlugin to provide the module conditionally:

// in webpack.customSettings.js
module.exports = {
  const customJsFilePath = 'path/to/custom/js/file';
  // alternatively, if no import is desired:
  // const customJsFilePath = null;
};

// in webpack.config.js
const settings = require('./webpack.customSettings.js');
// ...
new webpack.ProvidePlugin((() => {
  const addModules = {};

  if (settings.customJsFilePath) {
    addModules['window.myFunc'] = [settings.customJsFilePath, 'default'];
  }

  return addModules;
})()),

// in my main index.js
if (window.myFunc) {
  window.myFunc();
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.