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
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);
})
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:
For include to bundle only useful files I write theme-customize-loader. It`s webpack loader.
$ npm install theme-customize-loader --save-dev
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.
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');
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With