Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Webpack check file exist and import in condition

I use webpack in my react project.

I want check file in 'foo/myfile' and if that file exist import in my component, or load from 'bar/myfile'. for example:

let myModule;
if(webpackCheckFileExist('foo/myfile.jsx')){
  myModule = require('foo/myfile.jsx');
} else {
  myModule = require('bar/myfile.jsx');
}

I try:

if(__webpack_modules__[require.resolveWeak("foo/myfile.jsx")]) {
  // do something when mod1 is available
}

but if file dosnt exist - i catch webpack error

like image 799
nDiviD Avatar asked Dec 06 '16 09:12

nDiviD


2 Answers

You can use require.context and a regular expression to match files in the current folder, see the code below.

const requireCustomFile = require.context(
    './', false, /custom.js$/
)

requireCustomFile.keys().forEach(fileName => {
    requireCustomFile(fileName);
})
like image 67
Leandro Salvatti Piscke Avatar answered Oct 02 '22 20:10

Leandro Salvatti Piscke


First of all: Use that method if you doesn`t want create one more chunk. For example: for use different preview files in you package in different projects and want have fallback without include to main package`s chunk. For other cases create additional chunk is better way.

Checking file for exist - not best idea. Config file such better because:

  1. manipulate structure without remove files;
  2. easy detect changes;

For include to bundle only useful files I write theme-customize-loader. It`s webpack loader.

  1. Add package $ npm install theme-customize-loader --save-dev
  2. Add config file in your app

    const data = {
      MyModule: {
        Single : 'App/components/single/Single.jsx',
        Preview: 'my-theme/Preview',
      },
      OtherModule: {
        Preview: false,
      },
    };
    
    module.exports = data;
    

    Value can be path to file or false for fallback file.

  3. Add to webpack configuration to rules section

    {
      enforce: 'pre',
      test   : /\.jsx$/,
      exclude: /node_modules/,
      use    : [{ loader: 'theme-customize-loader', options: { config: customizeConfig } }],
    },
    

    don`t forget import config file: const customizeConfig = require('./App/configs/customize');

  4. Use in file. Important: In one string

    let loadComponent;
    /* customize path: "MyModule.Preview" var: "loadComponent" name: "my-chunk-name" origin: "../components/OriginPreview.jsx" */
    

More info you can find here: https://www.npmjs.com/package/theme-customize-loader

like image 31
nDiviD Avatar answered Oct 02 '22 20:10

nDiviD