for example if I want to add require("index.less")
to all files and ignore this line if the file does not exists.
how do I do it (including using of loaders for example).
Asked
Active
Viewed 4,838 times
8

Vitali Zaidman
- 899
- 1
- 9
- 24
3 Answers
7
One option would be to set up require.context and then check if the file exists against that.
Rough idea:
var req = require.context('./', false, /^index.less$/);
if(req.keys().includes('./index.less')) {
req('./index.less');
}

musa
- 1,050
- 4
- 15
- 26

Juho Vepsäläinen
- 26,573
- 12
- 79
- 105
1
What I ended doing was improving the imports loader to add an option to import a less
file for every jsx
file with the same name if it exists.
My improved import loader
: https://github.com/welldone-software/imports-loader
The pull request: https://github.com/webpack/imports-loader/pull/12
For example dropping mainview.less
in the same directory as mainview.jsx
, would add a require("mainview.less")
import to the top of the jsx
file:
loaders: [
{ test: /\.jsx?$/, loaders: ['imports?null=[./{name}.less]', 'react-hot', 'babel'] },
{ test: /\.less$/, loader: 'style!css!less' }
]

Vitali Zaidman
- 899
- 1
- 9
- 24
1
imports-loader
with includes
does the trick:
{
test: /\/index\.jsx$/,
include: (modulePath) => fs.existsSync(path.join(path.dirname(modulePath), 'style.sass')),
use: [
{
loader: 'imports-loader',
options: {
imports: 'side-effects ./style.sass'
}
}
]
}

user1355585
- 33
- 1
- 5