8

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).

4

3 回答 3

7

一种选择是设置require.context然后检查文件是否存在。

粗略的想法:

var req = require.context('./', false, /^index.less$/);

if(req.keys().includes('./index.less')) {
  req('./index.less');
}
于 2015-08-22T06:23:45.530 回答
1

imports-loaderincludes诀窍:

{
  test: /\/index\.jsx$/,
  include: (modulePath) => fs.existsSync(path.join(path.dirname(modulePath), 'style.sass')),
  use: [
    {
      loader: 'imports-loader',
      options: {
        imports: 'side-effects ./style.sass'
      }
    }
  ]
}
于 2020-12-14T09:11:43.773 回答
1

我最终做的是改进导入加载器,以添加一个选项,以便less为每个jsx同名文件(如果存在)导入文件。

我的改进import loaderhttps ://github.com/welldone-software/imports-loader

拉取请求:https ://github.com/webpack/imports-loader/pull/12

例如,mainview.less放在与 , 相同的目录中mainview.jsx会在文件顶部添加一个require("mainview.less")导入jsx

loaders: [
    { test: /\.jsx?$/, loaders: ['imports?null=[./{name}.less]', 'react-hot', 'babel'] },
    { test: /\.less$/, loader: 'style!css!less' }
]
于 2015-08-23T07:26:30.260 回答