Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

webpack try to require a module that might be missing

Tags:

webpack

I want to try to require a module in a webpack build and if that file is not found just do nothing, don't throw an error etc.

I tried doing it this way:

try {
  const local = require('./config-local.js');
  extend(config, local);
} catch (err) {
  // do nothing here
}

Basically what I want to do is to extend a config object with a local config if that file is found but if it isn't just don't extend it with anything.

Webpack throws an error that module is missing even though that require is wrapped in a try/catch clause.

How to tell webpack to ignore it?

like image 866
kamilkp Avatar asked Apr 30 '16 18:04

kamilkp


People also ask

How import works in webpack?

The chunk will be fetched on the first call to import() , and subsequent calls to import() will use the same network response. Note that this only makes sense in the case of a partially dynamic statement, e.g. import(`./locales/${language}. json`) , where multiple module paths that can potentially be requested.

What is webpackChunkName?

webpackChunkName: A name for the new chunk. Since webpack 2.6. 0, the placeholders [index] and [request] are supported within the given string to an incremented number or the actual resolved filename respectively. You can use [request] placeholder to set dynamic chunk name.

Does Webpack use CommonJS?

As you may know, webpack supports a couple of module types out of the box, including both CommonJS and ES modules. Webpack also works on both client- and server-side JavaScript, so with webpack, we can also easily handle assets and resources like images, fonts, stylesheets, and so on.


1 Answers

Based on @trysis comment, I ended up doing this in my project:

const REQUIRE_TERMINATOR = '';
try {
  const local = require(`./config-local.js${REQUIRE_TERMINATOR}`);
  extend(config, local);
} catch (err) {
  // do nothing here
}

This will give WebPack enough information to include all files starting with config-local.js (which will be exactly the file you want), but also confuse it enough that it won't try to verify file's existence ahead of time, so your try/catch block will trigger during runtime.

like image 139
panta82 Avatar answered Jan 26 '23 00:01

panta82