Giter Site home page Giter Site logo

less-loader's Introduction

npm node tests cover discussion size

less-loader

A Less loader for webpack. Compiles Less to CSS.

Getting Started

To begin, you'll need to install less and less-loader:

npm install less less-loader --save-dev

or

yarn add -D less less-loader

or

pnpm add -D less less-loader

Then add the loader to your webpack config. For example:

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.less$/i,
        use: [
          // compiles Less to CSS
          "style-loader",
          "css-loader",
          "less-loader",
        ],
      },
    ],
  },
};

And run webpack via your preferred method.

Options

lessOptions

Type:

type lessOptions = import('less').options | ((loaderContext: LoaderContext) => import('less').options})

Default: { relativeUrls: true }

You can pass any Less specific options to the less-loader through the lessOptions property in the loader options. See the Less documentation for all available options in dash-case. Since we're passing these options to Less programmatically, you need to pass them in camelCase here:

object

Use an object to pass options through to Less.

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.less$/i,
        use: [
          {
            loader: "style-loader",
          },
          {
            loader: "css-loader",
          },
          {
            loader: "less-loader",
            options: {
              lessOptions: {
                strictMath: true,
              },
            },
          },
        ],
      },
    ],
  },
};

function

Allows setting the options passed through to Less based off of the loader context.

module.exports = {
  module: {
    rules: [
      {
        test: /\.less$/i,
        use: [
          "style-loader",
          "css-loader",
          {
            loader: "less-loader",
            options: {
              lessOptions: (loaderContext) => {
                // More information about available properties https://webpack.js.org/api/loaders/
                const { resourcePath, rootContext } = loaderContext;
                const relativePath = path.relative(rootContext, resourcePath);

                if (relativePath === "styles/foo.less") {
                  return {
                    paths: ["absolute/path/c", "absolute/path/d"],
                  };
                }

                return {
                  paths: ["absolute/path/a", "absolute/path/b"],
                };
              },
            },
          },
        ],
      },
    ],
  },
};

additionalData

Type:

type additionalData =
  | string
  | ((content: string, loaderContext: LoaderContext) => string);

Default: undefined

Prepends/Appends Less code to the actual entry file. In this case, the less-loader will not override the source but just prepend the entry's content.

This is especially useful when some of your Less variables depend on the environment:

Since you're injecting code, this will break the source mappings in your entry file. Often there's a simpler solution than this, like multiple Less entry files.

string

module.exports = {
  module: {
    rules: [
      {
        test: /\.less$/i,
        use: [
          "style-loader",
          "css-loader",
          {
            loader: "less-loader",
            options: {
              additionalData: `@env: ${process.env.NODE_ENV};`,
            },
          },
        ],
      },
    ],
  },
};

function

Sync
module.exports = {
  module: {
    rules: [
      {
        test: /\.less$/i,
        use: [
          "style-loader",
          "css-loader",
          {
            loader: "less-loader",
            options: {
              additionalData: (content, loaderContext) => {
                // More information about available properties https://webpack.js.org/api/loaders/
                const { resourcePath, rootContext } = loaderContext;
                const relativePath = path.relative(rootContext, resourcePath);

                if (relativePath === "styles/foo.less") {
                  return "@value: 100px;" + content;
                }

                return "@value: 200px;" + content;
              },
            },
          },
        ],
      },
    ],
  },
};
Async
module.exports = {
  module: {
    rules: [
      {
        test: /\.less$/i,
        use: [
          "style-loader",
          "css-loader",
          {
            loader: "less-loader",
            options: {
              additionalData: async (content, loaderContext) => {
                // More information about available properties https://webpack.js.org/api/loaders/
                const { resourcePath, rootContext } = loaderContext;
                const relativePath = path.relative(rootContext, resourcePath);

                if (relativePath === "styles/foo.less") {
                  return "@value: 100px;" + content;
                }

                return "@value: 200px;" + content;
              },
            },
          },
        ],
      },
    ],
  },
};

sourceMap

Type:

type sourceMap = boolean;

Default: depends on the compiler.devtool value

By default generation of source maps depends on the devtool option. All values enable source map generation except eval and false value.

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.less$/i,
        use: [
          "style-loader",
          {
            loader: "css-loader",
            options: {
              sourceMap: true,
            },
          },
          {
            loader: "less-loader",
            options: {
              sourceMap: true,
            },
          },
        ],
      },
    ],
  },
};

webpackImporter

Type:

type webpackImporter = boolean;

Default: true

Enables/Disables the default webpack importer.

This can improve performance in some cases. Use it with caution because aliases and @import from node_modules will not work.

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.less$/i,
        use: [
          "style-loader",
          "css-loader",
          {
            loader: "less-loader",
            options: {
              webpackImporter: false,
            },
          },
        ],
      },
    ],
  },
};

implementation

Type:

type implementation = object | string;

less-loader compatible with Less 3 and 4 versions

The special implementation option determines which implementation of Less to use. Overrides the locally installed peerDependency version of less.

This option is only really useful for downstream tooling authors to ease the Less 3-to-4 transition.

object

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.less$/i,
        use: [
          "style-loader",
          "css-loader",
          {
            loader: "less-loader",
            options: {
              implementation: require("less"),
            },
          },
        ],
      },
    ],
  },
};

string

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.less$/i,
        use: [
          "style-loader",
          "css-loader",
          {
            loader: "less-loader",
            options: {
              implementation: require.resolve("less"),
            },
          },
        ],
      },
    ],
  },
};

lessLogAsWarnOrErr

Type:

type lessLogAsWarnOrErr = boolean;

Default: false

Less warnings and errors will be webpack warnings and errors, not just logs.

warning.less

div {
  &:extend(.body1);
}

If lessLogAsWarnOrErr is set to false it will be just a log and webpack will compile successfully, but if you set this option to true webpack will compile fail with a warning.

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.less$/i,
        use: [
          "style-loader",
          "css-loader",
          {
            loader: "less-loader",
            options: {
              lessLogAsWarnOrErr: true,
            },
          },
        ],
      },
    ],
  },
};

Examples

Normal usage

Chain the less-loader with the css-loader and the style-loader to immediately apply all styles to the DOM.

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.less$/i,
        use: [
          {
            loader: "style-loader", // creates style nodes from JS strings
          },
          {
            loader: "css-loader", // translates CSS into CommonJS
          },
          {
            loader: "less-loader", // compiles Less to CSS
          },
        ],
      },
    ],
  },
};

Unfortunately, Less doesn't map all options 1-by-1 to camelCase. When in doubt, check their executable and search for the dash-case option.

Source maps

To enable sourcemaps for CSS, you'll need to pass the sourceMap property in the loader's options. If this is not passed, the loader will respect the setting for webpack source maps, set in devtool.

webpack.config.js

module.exports = {
  devtool: "source-map", // any "source-map"-like devtool is possible
  module: {
    rules: [
      {
        test: /\.less$/i,
        use: [
          "style-loader",
          {
            loader: "css-loader",
            options: {
              sourceMap: true,
            },
          },
          {
            loader: "less-loader",
            options: {
              sourceMap: true,
            },
          },
        ],
      },
    ],
  },
};

If you want to edit the original Less files inside Chrome, there's a good blog post. The blog post is about Sass but it also works for Less.

In production

Usually, it's recommended to extract the style sheets into a dedicated file in production using the MiniCssExtractPlugin. This way your styles are not dependent on JavaScript.

Imports

First we try to use built-in less resolve logic, then webpack resolve logic.

Webpack Resolver

webpack provides an advanced mechanism to resolve files. less-loader applies a Less plugin that passes all queries to the webpack resolver if less could not resolve @import. Thus you can import your Less modules from node_modules.

@import "bootstrap/less/bootstrap";

Using ~ is deprecated and can be removed from your code (we recommend it), but we still support it for historical reasons. Why you can removed it? The loader will first try to resolve @import as relative, if it cannot be resolved, the loader will try to resolve @import inside node_modules.

Default resolver options can be modified by resolve.byDependency:

webpack.config.js

module.exports = {
  devtool: "source-map", // any "source-map"-like devtool is possible
  module: {
    rules: [
      {
        test: /\.less$/i,
        use: ["style-loader", "css-loader", "less-loader"],
      },
    ],
  },
  resolve: {
    byDependency: {
      // More options can be found here https://webpack.js.org/configuration/resolve/
      less: {
        mainFiles: ["custom"],
      },
    },
  },
};

Less Resolver

If you specify the paths option, modules will be searched in the given paths. This is less default behavior. paths should be an array with absolute paths:

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.less$/i,
        use: [
          {
            loader: "style-loader",
          },
          {
            loader: "css-loader",
          },
          {
            loader: "less-loader",
            options: {
              lessOptions: {
                paths: [path.resolve(__dirname, "node_modules")],
              },
            },
          },
        ],
      },
    ],
  },
};

Plugins

In order to use plugins, simply set the plugins option like this:

webpack.config.js

const CleanCSSPlugin = require('less-plugin-clean-css');

module.exports = {
  ...
    {
      loader: 'less-loader',
      options: {
        lessOptions: {
          plugins: [
            new CleanCSSPlugin({ advanced: true }),
          ],
        },
      },
    },
  ...
};

Note

Access to the loader context inside the custom plugin can be done using the pluginManager.webpackLoaderContext property.

module.exports = {
  install: function (less, pluginManager, functions) {
    functions.add("pi", function () {
      // Loader context is available in `pluginManager.webpackLoaderContext`

      return Math.PI;
    });
  },
};

Extracting style sheets

Bundling CSS with webpack has some nice advantages like referencing images and fonts with hashed urls or hot module replacement in development. In production, on the other hand, it's not a good idea to apply your style sheets depending on JS execution. Rendering may be delayed or even a FOUC might be visible. Thus it's often still better to have them as separate files in your final production build.

There are two possibilities to extract a style sheet from the bundle:

CSS modules gotcha

There is a known problem with Less and CSS modules regarding relative file paths in url(...) statements. See this issue for an explanation.

Contributing

Please take a moment to read our contributing guidelines if you haven't yet done so.

CONTRIBUTING

License

MIT

less-loader's People

Contributors

adi-pjackson avatar alexander-akait avatar anshumanv avatar cap-bernardito avatar dependabot[bot] avatar ersachin3112 avatar evilebottnawi avatar haspatrickc avatar jhnns avatar joshwiens avatar jpvanhal avatar kevinzwhuang avatar mattlewis92 avatar mfellner avatar michael-ciniawsky avatar mistic avatar mtscout6 avatar munter avatar n1ru4l avatar prestancedesign avatar simon04 avatar sliwey avatar snitin315 avatar soilspoon avatar sokra avatar sophiebits avatar spacek33z avatar thelarkinn avatar wolever avatar ztamizzen avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

less-loader's Issues

import url?

Hi, Im trying to parse the LESS from the material-ui.com project and get the following error:

ERROR in multi main
Module not found: Error: Cannot resolve module 'www/material-ui.css' in /Users/mg/Documents/js/scaffold-web-rx
 @ multi main

ERROR in ./src/material-ui.less
Module parse failed: /Users/mg/Documents/js/scaffold-web-rx/node_modules/less-loader/index.js!/Users/mg/Documents/js/scaffold-web-rx/src/material-ui.less Line 1: Unexpected token ILLEGAL
You may need an appropriate loader to handle this file type.
| @import url('http://fonts.googleapis.com/css?family=Roboto:300,400,500');
| /*! normalize.css v3.0.2 | MIT License | git.io/normalize */
| /**
 @ multi main

Heres my webpack config:

var webpack = require('webpack'),
    path    = require('path');

module.exports = {
    entry: './src/index.jsx',
    devtool: 'source-map',
    output: {
        path: path.join(__dirname, 'www'),
        filename: 'app.js'
    },
    resolve: {
        modulesDirectories: ['node_modules'],
    },
    module: {
        loaders: [
            { test: /\.css$/, loader: 'style!css' },
            { test: /\.less$/, loader: 'less' },
            { test: /\.jsx$/, loader: 'jsx-loader?harmony&insertPragma=React.DOM' },
            { test: /\.js$/, loader: '6to5-loader'},
            { test: /\.(eot|woff)$/, loader: 'file' },
        ]
    }
};

and the materialui.

@import "~material-ui/src/less/scaffolding.less";
@import "~material-ui/src/less/components.less";

Do I need some special loader for url or is there something else going on here?

Imports Out of Order in Output

I'm using the Extract Text Plugin with less-loader to import a main.less files with several imports. I have a reset LESS stylesheet at the beginning which should start at the beginning of the compiled CSS. However, my imports are not being output in order. It works fine when I use the regular lessc compiler.

modifyVar not being passed from query string

I am trying to inject variables into less-loader with the modifyVars option. The loader configuration looks something like this:

ExtractTextPlugin.extract('style-loader',
                'css?module&importLoaders=2&localIdentName=[hash:base64:5]' +
                '!postcss!less?modifyVars="theme-main=red"');

I expected this to set the @theme-main variable to red, but I got this error instead:

ERROR in ../~/css-loader?module&importLoaders=2&localIdentName=[path][name]---[local]---[hash:base64:5]
!../~/postcss-loader!../~/less-loader?modifyVar="theme-main=red"
!./components/stylesheets/Tabs.less
    Module build failed: variable @theme-main is undefined
     @ /path/to/variables.less (line 62, column 16)
     near lines:

       @brand-primary: @theme-main;

Did I make a mistake in the query string syntax? What is the accepted way of passing parameterized options into less with the loader?

Require not finding .less files

I have an app with the following structure

app/
build/
styles/
  - app.less
...
client.js
webpack.config.js
...

client.js is the entry point for Webpack config. Inside client.js, I am requiring app.less by require('./styles/app.less).

Snippet of the config.js:

// client.js
import app from './app';

require('./styles/app.less');
......

Snippet of webpack.config.js:

// webpack.config.js
.....
entry: './client.js',
output: {
      path: './build/dist',
      publicPath: '/public/dist/',
      filename: '[name].js',
      chunkFilename: '[id].js'
 },
 module: {
       loaders: [{
              test: /\.less$/,
              loader: ExtractTextPlugin.extract('style-loader', 'css-loader!less-loader')
              }, {
 .....

When I build the files with Webpack, there are no .css files that are compiled inside my build/dist/ folder. In the browser, it shows " cannot find module './styles/app.less' "

Is the mixing of ES6 imports and require causing the problem?

Any help would be greatly appreciated. Thanks.

generating SourceMap

following up on @mtscout6 SourceMap implementation.
I have the following issue.
If i call this:

loader: 'style!css?modules&importLoaders=2&sourceMap&localIdentName=[local]!autoprefixer?browsers=last 2 version!less?outputStyle=expanded&sourceMap' 

everything works as supposed.

But if write something like:

loader: 'style!css?modules&importLoaders=2&sourceMap&localIdentName=[local]___[hash:base64:5]!autoprefixer?browsers=last 2 version!less?outputStyle=expanded&sourceMap' 

then the sourceMap doesn't have the generated appended hash values ( ie: ___rhfs2), while the CSS does have it.

What am i doing wrong ?

Less function svg-gradient and url-loader conflict

Using the svg-gradient function will transform this:

div {
  background-image: svg-gradient(to right, red, green 30%, blue);
}

to this:

div {
  background-image: url('data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiA/PjxzdmcgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB2ZXJzaW9uPSIxLjEiIHdpZHRoPSIxMDAlIiBoZWlnaHQ9IjEwMCUiIHZpZXdCb3g9IjAgMCAxIDEiIHByZXNlcnZlQXNwZWN0UmF0aW89Im5vbmUiPjxsaW5lYXJHcmFkaWVudCBpZD0iZ3JhZGllbnQiIGdyYWRpZW50VW5pdHM9InVzZXJTcGFjZU9uVXNlIiB4MT0iMCUiIHkxPSIwJSIgeDI9IjEwMCUiIHkyPSIwJSI+PHN0b3Agb2Zmc2V0PSIwJSIgc3RvcC1jb2xvcj0iI2ZmMDAwMCIvPjxzdG9wIG9mZnNldD0iMzAlIiBzdG9wLWNvbG9yPSIjMDA4MDAwIi8+PHN0b3Agb2Zmc2V0PSIxMDAlIiBzdG9wLWNvbG9yPSIjMDAwMGZmIi8+PC9saW5lYXJHcmFkaWVudD48cmVjdCB4PSIwIiB5PSIwIiB3aWR0aD0iMSIgaGVpZ2h0PSIxIiBmaWxsPSJ1cmwoI2dyYWRpZW50KSIgLz48L3N2Zz4=')
}

Which is problematic since webpack will then try and fail to resolve 'file' or 'directory', since no file actually exists.

Looking at the url-loader it may make sense to fix there, but sense my issue is currently tied to less I'm reporting it here.

less dependency missing

Hey,
You fixed less as a peer dependency issue a month ago (here), but didn't make a tag out of it.

I'm using library called font-awesome-webpack which uses your latest tag but because of it, it won't work on npm3.

Please upgrade, and thanks in advance.

UNMET PEER DEPENDENCY less@^2.3.1

Hey,

I keep getting "UNMET PEER DEPENDENCY less@^2.3.1" when i try to install less-loader via npm.

Any idea for a solution?

Best regards
Oliwer H.

fileLoader prevents less's @import from sharing variable/mixin context with imported less files

for example:

@import "variables.less"; // declares variables
@import "mixins.less"; // declares mixins
@import "some_styles.less"; // declares styles, relies on variables / mixins

because the file loader is effectively compiling each sub-import individually, the context is not being shared. If I just delete the fileLoader method from the code and use the built-in one, it works as expected.

This is a problem because many third-party tools, libraries and themes rely on this mechanism and using them with webpack shouldn't require adapting them to the loader's peculiarities.

Styles are not loaded

I've speent a lot of time trying to make it work, but something is missing for me. I've set up loader & webpack config accordingly, but if I require any *.less file - these files are not added to document.

On top of that, "~" alias does not work in my .less files. Here is webpack output if I try to compile with ~ alias in *.less file:

ERROR in ./~/css-loader!./~/less-loader!./src/less/main.less
Module build failed: '~material-ui/src/less/scaffolding.less' wasn't found
 @ D:\WebServers\custom_home\brainfock.dev\app\react-flux-backbone-app\src\less\
main.less (line 3, column 1)
 near lines:

    @import "~material-ui/src/less/scaffolding.less";
   // @import "node_modules/material-ui/src/less/scaffolding.less";
 @ ./src/less/main.less 4:14-340

ERROR in ./src/less/main.less
Module build failed: Error: Didn't get a result from child compiler
    at Object.<anonymous> (D:\WebServers\custom_home\brainfock.dev\app\react-flu
x-backbone-app\node_modules\extract-text-webpack-plugin\loader.js:90:22)
    at Tapable.<anonymous> (D:\WebServers\custom_home\brainfock.dev\app\react-fl
ux-backbone-app\node_modules\webpack\lib\Compiler.js:210:10)
    at D:\WebServers\custom_home\brainfock.dev\app\react-flux-backbone-app\node_
modules\webpack\lib\Compiler.js:397:12
    at Tapable.next (D:\WebServers\custom_home\brainfock.dev\app\react-flux-back
bone-app\node_modules\webpack\node_modules\tapable\lib\Tapable.js:69:11)
    at Object.<anonymous> (D:\WebServers\custom_home\brainfock.dev\app\react-flu
x-backbone-app\node_modules\extract-text-webpack-plugin\loader.js:77:5)
    at Tapable.next (D:\WebServers\custom_home\brainfock.dev\app\react-flux-back
bone-app\node_modules\webpack\node_modules\tapable\lib\Tapable.js:71:37)
    at CachePlugin.<anonymous> (D:\WebServers\custom_home\brainfock.dev\app\reac
t-flux-backbone-app\node_modules\webpack\lib\CachePlugin.js:40:4)
    at Tapable.applyPluginsAsync (D:\WebServers\custom_home\brainfock.dev\app\re
act-flux-backbone-app\node_modules\webpack\node_modules\tapable\lib\Tapable.js:7
3:13)
    at Tapable.<anonymous> (D:\WebServers\custom_home\brainfock.dev\app\react-fl
ux-backbone-app\node_modules\webpack\lib\Compiler.js:394:9)
    at Tapable.<anonymous> (D:\WebServers\custom_home\brainfock.dev\app\react-fl
ux-backbone-app\node_modules\webpack\lib\Compilation.js:529:13)
Child extract-text-webpack-plugin:
        + 1 hidden modules

    ERROR in ./~/css-loader!./~/less-loader!./src/less/main.less
    Module build failed: '~material-ui/src/less/scaffolding.less' wasn't found
     @ D:\WebServers\custom_home\brainfock.dev\app\react-flux-backbone-app\src\l
ess\main.less (line 3, column 1)
     near lines:

If I remove "~" form @import url then there are no errors while compiling with webpack, but all contents of less files are still ignored. So webpack does parse them, but does not include.
Please, suggest a fix. I really doubt this is webpack-less loader issue but something on my end. I tried updating all dependencies to latest, clearing npm modules, re-installing.
Thanks!

Feature request for dynamic modifyVars

I would like to have a single configuration for mobile, tablet and desktop entries so you don't have to start 3 webpack instances with different configs for each device. See my example below.

I know that media queries exists but I need to strip out unnecessary css (My market is sensitive to file sizes) without ruin the less source maps.

If there is any other way of doing this feel free to tell me.

webpack.config.js

var path = require('path'),
  ExtractTextPlugin = require('extract-text-webpack-plugin');

module.exports = {
  devtool: 'source-map',
  entry: {
    mobile: './app/index',
    tablet: './app/index',
    desktop: './app/index'
  },
  output: {
    filename: '[name].js',
    path: path.join(__dirname, 'dist')
  },
  module: {
    loaders: [
      {
        test: /\.less$/,
        loader: ExtractTextPlugin.extract(
          'css?sourceMap!less?{"sourceMap":"", "modifyVars":{"device":"[name]"}}'
        )
      }
    ]
  },
  plugins: [
    new ExtractTextPlugin('[name].css')
  ]
};

app/index.js

require('./index.less');

app/index.less

body {
  // Include style to all devices
  & when(@device = mobile) {
    // Only for mobile
  }
  & when(@device = tablet) {
    // Only for tablet
  }
  & when(@device = desktop) {
    // Only for desktop
  }
}

Doesn't use moduleDirectories

I'm currently using less and bootstrap in my project. I'm importing some bootstrap less files like this:

@import "bootstrap/less/reset";
@import "bootstrap/less/grid";

and in my webpack config I have

config.resolve.modulesDirectories = ["components", "node_modules"];

but the imports can't be resolved.

How to add a plugin (string replace) ?

Hi
I need to replace a string in my less files before they get compiled. But I can't figure out how to add a less plugin, the documentation is not really helpful here.

This is the important part of my webpack.config:

  // LESS LOADER
  var lessLoader = {
    test: /\.less$/,
    loader: (!BUILD || TEST) ? 'style!css!less!postcss' :
      // Extract less/css files in production builds
      ExtractTextPlugin.extract(
        'css?sourceMap!less?sourceMap!postcss'
        )
  };

  // Add cssLoader to the loader list
  config.module.loaders.push(lessLoader);

My question is, how do I get a less-loader plugin into that config shown above that can replace strings in the less files before they get processed?

Thank you
Bernd

Module build failed: variable is undefined

I'm switching from RequireJS to webpack, and I'm trying to use less-loader and extract-text-webpack-plugin to create a CSS file for my entry point. Here's the relevant part of my webpack.config.js:

var ExtractTextPlugin = require("extract-text-webpack-plugin");
module.exports = {
    entry: {
        teacher: '../js/teacher'
    },
    module: {
        loaders: [
            {
                test: /\.less$/,
                loader: ExtractTextPlugin.extract("style-loader", "css-loader!less-loader")
            }
        ]
    },
    plugins: [
        new ExtractTextPlugin('../css/[name].min.css'),
    ]
    ...
}

And this is the first line of my teacher.js entry file:

require('../css/teacher.less');

My configuration seems right, but I'm getting this error when I run webpack -d:

Module build failed: variable @semiLightOrange is undefined

Here's what I have in teacher.less:

@import "main.less";
@import "question.less";

And here's what I have in main.less:

@import "main-colors.less"; /* <-- @semiLightOrange is defined here */

And then I'm trying to reference @semiLightOrange in question.less. Since I'm importing main.less before question.less why does less-loader say the variable is undefined? Does it have something to do with the intermediate import of main-colors.less?

Problem loading a data-uri after updating to 2.0.0

Likely user error, but I can't seem to figure it out...

I just updated a number of packages, including updating the less-loader to version 2.0.0. In the process of doing those updates using a data-uri in my less file seems to have broke:

background-image: data-uri('image/svg+xml;charset=UTF-8', 'dropIndicator.svg');

When I do that I get this error message:

ERROR in ./~/css-loader!./~/less-loader!./src/birch/style/style.less
Module build failed: error evaluating function `data-uri`: Cannot 'resolveSync' because the fileSystem is not sync. Use 'resolve'!
 @ /Users/jesse/Dropbox/Projects:Hacks/Birch/src/birch/style/style.less (line 267, column 19)
 near lines:
    content: "";
    background-image: data-uri('image/svg+xml;charset=UTF-8', 'dropIndicator.svg');
    background-repeat: no-repeat;
 @ ./src/birch/style/style.less 4:14-246

Can someone tell me what must be done to fix the problem? I'm not sure what is meant by the "Use 'resolve'!" suggestion in the error message.

Thanks,
Jesse

@import inserts duplicates

If you have file foo:

@import 'base.less';

.foo { ... }

and file bar:

@import 'base.less';

.bar { ... }

...and you webpack both foo and bar into the same bundle.js, the bundle will have two instances of all rules from base.less. (this is true even if using the dedupe plugin).

loading bootstrap problem

When trying to import bootstrap import Bootstrap from 'bootstrap/less/bootstrap.less';
I'm getting the following error:

ERROR in ./~/less-loader!./~/css-loader!./~/bootstrap/less/bootstrap.less
Module build failed: CssSyntaxError: /storage/safe/ogi-it/Projekte/LIMS/LIMS_src/LIMS_v2/node_modules/bootstrap/less/bootstrap.less:7:1: Unknown word
    at Input.error (/storage/safe/ogi-it/Projekte/LIMS/LIMS_src/LIMS_v2/node_modules/css-loader/node_modules/postcss/lib/input.js:61:21)
    at Parser.unknownWord (/storage/safe/ogi-it/Projekte/LIMS/LIMS_src/LIMS_v2/node_modules/css-loader/node_modules/postcss/lib/parser.js:479:26)
    at Parser.word (/storage/safe/ogi-it/Projekte/LIMS/LIMS_src/LIMS_v2/node_modules/css-loader/node_modules/postcss/lib/parser.js:174:14)
    at Parser.loop (/storage/safe/ogi-it/Projekte/LIMS/LIMS_src/LIMS_v2/node_modules/css-loader/node_modules/postcss/lib/parser.js:60:26)
    at parse (/storage/safe/ogi-it/Projekte/LIMS/LIMS_src/LIMS_v2/node_modules/css-loader/node_modules/postcss/lib/parse.js:25:12)
    at new LazyResult (/storage/safe/ogi-it/Projekte/LIMS/LIMS_src/LIMS_v2/node_modules/css-loader/node_modules/postcss/lib/lazy-result.js:57:24)
    at Processor.process (/storage/safe/ogi-it/Projekte/LIMS/LIMS_src/LIMS_v2/node_modules/css-loader/node_modules/postcss/lib/processor.js:36:16)
    at processCss (/storage/safe/ogi-it/Projekte/LIMS/LIMS_src/LIMS_v2/node_modules/css-loader/lib/processCss.js:165:11)
    at Object.module.exports (/storage/safe/ogi-it/Projekte/LIMS/LIMS_src/LIMS_v2/node_modules/css-loader/lib/loader.js:22:2)
 @ ./~/bootstrap/less/bootstrap.less 4:14-100

line 7 of bootstrap.less contains a comment :// Core variables and mixing
any ideas how to fix?

Variable not accessible using Require includes.

I'm using Wepack and the Less-loader to package all my JavaScript and CSS in a single file. I'm using the require syntax to import my LESS. For example,
require('base.less');
require('more.less');

Unfortunately, any variables defined in base are not accessible in any file required after it. I would think this would work and be resolved by the loader. Am I mistaken?

Create source maps

It would be very helpful if there was some way to emit source maps for .less files.

Error while compiling less files

In my terminal i ran Maheshs-MacBook-Pro:sample mahesh$ node_modules/.bin/webpack --module-bind 'less=style!css!less'
I am getting below error
ERROR in .//css-loader!.//less-loader!.//style-loader!.//css-loader!.//less-loader!.//bootstrap/less/bootstrap.less
Module build failed: Unrecognised input

Error with less parser

Hey! Ran into this and been trying to figure out a pull request instead of an issue for you but no luck. I think it's because the less parser uses relative paths but the less-loader is using absolute paths. getInput() in lib/less/parser.js is returning undefined. Running node v0.8.1.

kyle@office:/var/www/jmpress.js$ grunt
path.existsSync is now called `fs.existsSync`.
Running "lint:files" (lint) task
Lint free.

Running "webpack:docs" (webpack) task

/var/www/jmpress.js/node_modules/grunt-webpack/node_modules/webpack/node_modules/less-loader/node_modules/less/lib/less/parser.js:212
                 n >= 0 && input.charAt(n) !== '\n';
                                 ^
TypeError: Cannot call method 'charAt' of undefined
    at getLocation (/var/www/jmpress.js/node_modules/grunt-webpack/node_modules/webpack/node_modules/less-loader/node_modules/less/lib/less/parser.js:212:34)
    at new LessError (/var/www/jmpress.js/node_modules/grunt-webpack/node_modules/webpack/node_modules/less-loader/node_modules/less/lib/less/parser.js:221:19)
    at Object.less.Parser.parser.parse.i [as toCSS] (/var/www/jmpress.js/node_modules/grunt-webpack/node_modules/webpack/node_modules/less-loader/node_modules/less/lib/less/parser.js:385:31)
    at /var/www/jmpress.js/node_modules/grunt-webpack/node_modules/webpack/node_modules/less-loader/node_modules/less/lib/less/index.js:22:56
    at less.Parser.parser.parse.finish (/var/www/jmpress.js/node_modules/grunt-webpack/node_modules/webpack/node_modules/less-loader/node_modules/less/lib/less/parser.js:434:40)
    at less.Parser.imports.imports.push (/var/www/jmpress.js/node_modules/grunt-webpack/node_modules/webpack/node_modules/less-loader/node_modules/less/lib/less/parser.js:94:48)
    at module.exports.less.Parser.importer.options.resolve.filename (/var/www/jmpress.js/node_modules/grunt-webpack/node_modules/webpack/node_modules/less-loader/index.js:30:7)
    at Object.less.Parser.parser.parse (/var/www/jmpress.js/node_modules/grunt-webpack/node_modules/webpack/node_modules/less-loader/node_modules/less/lib/less/parser.js:436:17)
    at /var/www/jmpress.js/node_modules/grunt-webpack/node_modules/webpack/node_modules/less-loader/index.js:29:9
    at fs.readFile (fs.js:176:14)

Using of extend feature from less

Is it possible to use extend notation in any form?

@extend .col-md-3;

This way I'm getting it skipped.

&:extend(.col-md-3);

This way I receive error in webpack

Module build failed: 
    .item {
      ^
      Invalid property name

@import url() strange bug

When I use
@import url("http://fonts.googleapis.com/css?family=Roboto:400,500&subset=latin,cyrillic");
somewhere in code for some reason all other styles disappeares and resulted CSS has only this line.

My webpack config:

/* jshint node: true */

var ExtractTextPlugin = require('extract-text-webpack-plugin');

module.exports = {
  entry: {
      page: './blocks/page/page.coffee'
  },
  output: {
    path: '../app/assets/',
    filename: 'javascripts/[name].js'
  },
  module: {
    loaders: [
        { test: /\.coffee$/, loader: 'coffee-loader' },
        {
          test: /\.less$/,
          loader: ExtractTextPlugin.extract('style-loader', 'css-loader!less-loader')
        }
    ]
  },
  plugins: [
      new ExtractTextPlugin('stylesheets/page.css', { allChunks: true })
  ]
};

Loader fails on SVG definition rules with URL values

The loader seems to break when .less files include references to SVG definitions. I'm using the markers in the styles because I don't want to mess with the charting library I'm using but the less loader breaks on the URL.

Marker definition:

<defs>
    <marker id="line-marker">
        <circle cx="6" cy="6" r="5"></circle>
    </marker>
</defs>

Marker use:

path.nv-line {
    marker-mid: url('#line-marker');
}

Is there a way of ignoring some URL values in the .less files or another way to prevent the loader from failing?

less-loader should rewrite url(...) in less files

Right now when trying to load bootstrap it fails because it tries to resolve url(...) extracted from already rendered CSS, of course url(...) are incorrect because they are relative to original filenames.

A simple fix:

if (/url\(/.exec(data)) {
  data = data.replace(/url\(([^\)]+)\)/g, function(_, url) {
    url = url.replace(/^(\\"|"|'|\\')/, '').replace(/(\\"|"|'|\\')$/, '');
    url = 'url(' + path.dirname(filename) + '/' + url + ')';
    return url;
  });
}

seems to work, but I've found that we can apply another patch to less compiler for a "cleaner" way to do that.

[question] moving from lessbuildify

I have a project that is using browserify and lessbuildify and I'm looking at moving to webpack/less-loader.

With lessbuildify when I require('path/to/main.less'), require('./foo.less'), require('./bar.less') instead of compiling individually, it builds a list and compiles a file it generates that simply contains a set of @includes. It would look something like this:

/* all the paths get expanded */
@include "path/to/main.less";
@include "full/path/to/foo.less";
@include "full/path/to/bar.less"

Is this possible or advisable with less-loader? The blocker in adopting less-loader is that foo.less and bar.less depend on variables defined in main.less but they have never needed to @include it explicitly. I think this might be bad practice, but I'm looking for a way forward that doesn't involve major changes to all of my less files.

note: my example is simplified and the actual main.less is actually a collection of files rather than one central file I should @include.

Fail to using extend feature from less

I wanna using extend feature , like this:

.flexBox {
    display: -webkit-flex;
    display: -moz-flex;
    display: -ms-flex;
    display: flex;
}
header {
     .flexBox
}

But got error msg like this :

Module build failed: ModuleError: CssSyntaxError: 
house-list.less:20:5: Unknown word
header {
    .flexBox;
    ^

with my webpack.config.js

...
module: {
        loaders: [
            { test: /\.vue$/, loader: vue.withLoaders({
                css: ExtractTextPlugin.extract(
                    "style-loader", "css-loader?sourceMap!less!cssnext-loader")
                }),
            },
            { test: /\.less$/, loader: ExtractTextPlugin.extract(
                "style-loader",'css-loader?sourceMap!less!cssnext-loader')
            },
            { test: /\.css$/, loader: ExtractTextPlugin.extract(
                "style-loader", "css-loader?sourceMap!cssnext-loader")
            },
            { test: /\.(jpg|png|gif)$/, loader: "file-loader?name=images/[hash].[ext]"},
            { test: /\.(html|tpl)$/, loader: 'html-loader' }
        ]
    },
...

How would I do this?

Fail to using @import

Hi have the current folder situation:

App
App/aphextwin/
App/aphextwin/aphextwin.less
App/aphextwin/aphexwtin.variables.less

Inside aphextwin.less I'm calling @import "aphextwin.variables.less";

From App/App.js I call
require('./aphextwin/aphextwin.less');

I keep receiving this error:

[1] ROUTER ERROR:   SyntaxError: /Users/bortignon/dev/react-redux-universal-hot-example/src/contai  ners/App/aphextwin/aphextwin.less: Unexpected token (1:1)
[1]
[1]   - > 1 | @import "./aphextwin/aphextwin.variables.less";
[1]

And this is my webpack setting

 module: {
    loaders: [
      { test: /\.js$/, exclude: /node_modules/, loaders: ['babel', 'eslint-loader']},
      { test: /\.json$/, loader: 'json-loader' },
      { test: /\.scss$/, loader: 'style!css?modules&importLoaders=2&sourceMap&localIdentName=[local]___[hash:base64:5]!autoprefixer?browsers=last 2 version!sass?outputStyle=expanded&sourceMap' },
      {test: /\.less$/,  loader: "style!css!less"},
      { test: webpackIsomorphicToolsPlugin.regular_expression('images'), loader: 'url-loader?limit=10240' }
    ]
  },

I tried all the possible variation of the pat I'm trying to import but nothing.

 @import "./aphextwin/aphextwin.variables.less";
 @import "./aphextwin.variables.less";
 @import "aphextwin.variables.less";

Module build failed: visitors[i].run is not a function

the main.less file is empty, and i'm getting:

ERROR in ./styles/main.less
Module build failed: visitors[i].run is not a function
 @ /Users/bnaya/dev/opensource/hasadna/open-budget-frontend/open-budget/app/styles/main.less (line null, column -1)
 near lines:



 @ ./scripts/main.coffee 3:2-29

less 1.7.5 installed

my webpack config:

loaders:
...
          {
            test: /\.less$/,
            loader: 'less-loader'
          }

js code:

      require("styles/main.less");

Usage with bootstrap

Hi,
I'm trying to use webpack with bootstrap using the less-loader. And I'm getting the following error:

Module build failed: Error: Cannot find module "../../bower_components/bootstrap/fonts/glyphicons-halflings-regular.woff2"
    at webpackMissingModule (webpack:///./src/styles/styles.less?./~/css-loader!./~/less-loader:2:4311)
    at Object.eval (webpack:///./src/styles/styles.less?./~/css-loader!./~/less-loader:2:4461)

This is my loader part of the config file:

module: {
    loaders: [
      {test: /\.(js|jsx)$/, loader: 'jsx-loader', exclude: [bowerDir, nodeModulesDir]},
      {test: /\.(js|jsx)$/, loader: 'babel-loader', exclude: [bowerDir, nodeModulesDir]},
      {test: /\.json/, loader: 'json-loader'},
      {test: /\.less$/, loader: ExtractTextPlugin.extract('style', 'css!less')},
      {test: /\.png$/,  loader: "url?limit=10000&mimetype=image/png" },
      {test: /\.woff$/, loader: "url?limit=10000&mimetype=application/font-woff" },
      {test: /\.ttf$/,  loader: "url?limit=10000&mimetype=application/octet-stream" },
      {test: /\.eot$/,  loader: "file" },
      {test: /\.svg$/,  loader: "url?limit=10000&mimetype=image/svg+xml" },

    ]
  },

Posted it in gitter, but I'm guessing it would hard to track there. Any ideas?

I'm having trouble setting up the absolute paths for an non-default directory structure

I've been chipping away at the features and I've had success doing a lot of things with webpack. One thing that has plagued me for sometime is setting up a directory structure where the conf, bower and node modules are stored in a directory that is a sibling of the directory where my custom modules are stored.

I'm receiving the following error

ERROR in Entry module not found: Error: Cannot resolve module coffee-loader in /usr/local/webprojects/webpack/app/modules
resolve module coffee-loader in /usr/local/webprojects/webpack/app/modules

Note that I was successfully working with my node and bower directories being in different places before. Something about the absolute path situation is messing my project up, since it is not on the same branch.

My project is laid out like the following:

project
    build
        bower_components
        node_modules
        bower.json
        package.json
        webpack.config.js
    app
        modules (custom/proprietary commonjs modules)
        php
        view (Phalcon Volt partials)
        config (json configs so that socket.io and php can both connect)
        public
            index.php
    dist
        [working stuff will go here and will be fetched in the debug PHP template]

test might go inside of build or on the top level

I've set it up like this since PHP compilation will be a feature of this framework/scaffold


var path = require('path');
var webpack = require('webpack');
var console = require('console');

var resolveBowerPath = function(componentPath) {
    return path.join(__dirname, 'bower_components', componentPath);
};
var resolveNodePath = function(componentPath) {
    return path.join(__dirname, 'node_modules', componentPath);
};
var resolveModulePath = function(itemPath) {
    var appPath = path.resolve('../app');
    return path.join(appPath, 'modules', itemPath);
};


console.log(resolveBowerPath(''));
console.log(resolveNodePath(''));
console.log(resolveModulePath(''));
console.log(path.resolve('../app') + '/public/bundle');


module.exports = {
    cache: true,
    context: resolveModulePath(''),

    entry: {
      entryMain: './entryMain'
//      entryLogin: './entryLogin'
    },

    output: {
//        path: __dirname + '/public/bundle',
        path: path.resolve('../app') + '/public/bundle',
        publicPath: '/bundle/',
        filename: "[name].bundle.js",
        chunkFilename: '[id].bundle.js'
    },

    resolve: {
//        root: resolveModulePath(''),
        root: [resolveBowerPath(''), resolveNodePath(''), resolveModulePath('')],
        // tells webpack to query these directories for modules
//        modulesDirectories: ['bower_components', 'node_modules'],
        modulesDirectories: [resolveBowerPath(''), resolveNodePath(''), resolveModulePath('')],
//        modulesDirectories: ['./bower_path', './node_modules', resolveModulePath('')],

        alias: {
            lodash: resolveBowerPath('/lodash/dist/lodash'),
            jquery: resolveBowerPath('/jquery/dist/jquery'),
            angular: resolveBowerPath('/angular/angular'),
            angularRouter: resolveBowerPath('/angular-ui-router/release/angular-ui-router'),
            angularCookies: resolveBowerPath('/angular-cookies/angular-cookies'),
            angularResource: resolveBowerPath('/angular-resource/angular-resource'),
        },
        extensions: [
            '',
            '.js', '.coffee',
            '.html', '.jade',
            '.css', '.styl', '.scss', '.less'
        ]        
    },
    plugins: [
        new webpack.ProvidePlugin({
            _: 'lodash',
        }),
        // this plugin makes webpack not only looking for package.json, but also for a bower.json with a main-field
        new webpack.ResolverPlugin([
            new webpack.ResolverPlugin.DirectoryDescriptionFilePlugin("bower.json", ["main"])
        ]),
        new webpack.DefinePlugin({
          VERSION: JSON.stringify('alpha'),
          DEVEL: true
        })
    ],

    module: {
        loaders: [
            // Exports Angular
            { test: /[\/]angular\.js$/, loader: "exports?angular" },
            // Script Loaders
//            { test: /\.coffee$/, loader: "coffee" },
            { test: /\.coffee$/, loader: "coffee-loader" },

            { test: /\.html$/, loader: "html" },
//            { test: /\.jade$/, loader: "jade" },
            { test: /\.jade$/, loader: "template-html-loader" },
            // Style Loaders, style! inlines the css into the bundle files
            { test: /\.css$/, loader: "style!css" },
            { test: /\.scss$/, loader: "style!css!sass" },
            { test: /\.less$/, loader: "style!css!less" },
            { test: /\.styl$/, loader: "style!css!stylus" }
        ]
    }

};

I've tried a variety of things and this is what I have at the moment. So, I'm missing something small and obvious right?

Obscure error when can't find an @import file

Took me some time to figure out why webpack was throwing:

node_modules/webpack/node_modules/webpack-core/lib/NormalModuleMixin.js:141
                throw new Error("callback(): The callback was already called.");

I didn't have any more information, didn't know which module it choked on.

Finally tracked it down to a .less file with an @import "lib/foo.less"; that was pointing to a file that didn't exist anymore.

Using [email protected] and [email protected]. My webpack config has this in its loaders:

{test: /\.less$/, loader: 'style-loader!css-loader!less-loader'}

Let me know if there is any other information I can provide to help?

ERROR in Object.keys called on non-object

I am working on a webpack-es6-angular (1.x) project and am trying to incorporate my styles. in webpack config:
{ test: /\.less$/, loader: 'style!css!less' }

When I add this:
require("./styles/app.less");

I get:
ERROR in Object.keys called on non-object @ ./app/styles/app.less 4:14-120

It's a really simple .less file, no imports or anything. I don't know how to debug it, or even whether or not it's really a less-loader problem.

image-size, image-width, image-height doesn't work correctly

For instance, we have "sub/variables.less" which contains:

@img-width: image-width("../img/test.png");

And if try to import "~sub/variables.less" in other file (the resolve.root is set correctly) via:

@import (reference) "~sub/variables.less";

the "less-loader" will throws exception:

Module build failed: error evaluating function `image-width`: Cannot 'resolveSync' because the fileSystem is not sync. Use 'resolve'!
 @ <full-path-to-file>/sub/less/variables.less

Cannot use modifyVars to modify a file path variable

less-loader appear to have some escaping issues when I try to modify a variable that includes a path:

  {
    test: /\.less$/,
    loader: 'less-loader',
    query: {
      modifyVars: {
        'root-path': '"../../../root/"',
      }
    }
  },

This appears to over write @root-path for simple values like 'root', but some combination of .., /, and " makes this fail.

edit: Looks like this fails because of this line:

var query = loaderUtils.parseQuery(this.query);

Import url tries to resolve directory

Upon trying to @import "ProximaNova-font.css";

I get this error:

./~/css-loader?importLoaders=2&localIdentName=[path][name]---[local]---[hash:base64:5]&url=false!./~/postcss-loader!./~/less-loader!./assets/styles/less/common/ProximaNova-font.css
Module build failed: Cannot resolve 'file' or 'directory' .///hello.myfonts.net/count/2da629.less in /home/joe/www/frontend/assets/styles/less/common
 @ /home/joe/www/frontend/assets/styles/less/common/ProximaNova-font.css (line 39, column 0)
 near lines:
   /* @import must be at top of file, otherwise CSS will not work */
   @import url('//hello.myfonts.net/count/2da629');

Error: Cannot resolve 'file' or 'directory' .///hello.myfonts.net/count/2da629.less in /home/joe/www/frontend/assets/styles/less/common
 @ /home/joe/www/frontend/assets/styles/less/common/ProximaNova-font.css (line 39, column 0)
 near lines:
   /* @import must be at top of file, otherwise CSS will not work */
   @import url('//hello.myfonts.net/count/2da629');

    at formatLessRenderError (/home/joe/www/frontend/node_modules/less-loader/index.js:173:12)
    at /home/joe/www/frontend/node_modules/less-loader/index.js:68:19
    at /home/joe/www/frontend/node_modules/less/lib/less/render.js:26:35
    at /home/joe/www/frontend/node_modules/less/lib/less/parse.js:62:33
    at Object.finish [as _finish] (/home/joe/www/frontend/node_modules/less/lib/less/parser/parser.js:180:28)
    at Object.ImportVisitor._onSequencerEmpty (/home/joe/www/frontend/node_modules/less/lib/less/visitors/import-visitor.js:35:14)
    at ImportSequencer.tryRun (/home/joe/www/frontend/node_modules/less/lib/less/visitors/import-sequencer.js:50:14)
    at Object.ImportVisitor.run (/home/joe/www/frontend/node_modules/less/lib/less/visitors/import-visitor.js:29:25)
    at Object.Parser.parse (/home/joe/www/frontend/node_modules/less/lib/less/parser/parser.js:189:22)
    at Object.parse (/home/joe/www/frontend/node_modules/less/lib/less/parse.js:61:18)
 @ ./~/css-loader?importLoaders=2&localIdentName=[path][name]---[local]---[hash:base64:5]&url=false!./~/postcss-loader!./~/less-loader!./assets/styles/less/common/common.less 3:10-273

I'm using the less loader in conjunction with the css module loader: my loader config is the following:

return 'style-loader!css-loader?importLoaders=2&localIdentName=[path][name]---[local]---[hash:base64:5]&url=false!postcss-loader!less-loader'

resolve.alias support

I'm trying to create a custom loader that would add an import for a file that has something I want all files to have (variables and mixins for example). I want this to be possible:

{
  resolve: {
    alias: {
      azGlobalLess: __dirname + '/app/global.less'
    }
  }
}

then I have a custom loader (global-less-imports-loader) that does:

module.exports = function(source) {
  return '@import "azGlobalLess";\n' + source;
};

then in my less

@import 'azGlobalLess';

This currently fails with:

ERROR in ..//css-loader!..//less-loader!../build/global-less-imports-loader.js!./components/states/login/index.less
Module build failed: Cannot resolve 'file' or 'directory' ./azGlobalLess.less in /Users/kentcdodds/Developer/alianza/atac5/app/components/states/login
@ /Users/kentcdodds/Developer/alianza/atac5/app/components/states/login/index.less (line 1, column 0)
near lines:

@import "azGlobalLess";
.location(LoginCtrl, {
@ ./components/states/login/index.less 4:14-336

Obviously, I believe the custom loader bit is irrelevant. What I really need to get working is the resolve.alias working for less-loader. Am I doing something wrong?

Issue with less global-var

We use bower to manage our client dependencies. A number of these define a global variable @{bower_path} which we pass to lessc via the --global-var command line flag.

I understand that in less-loader we would need this to just be replaced with ~ so I wrote a loader that does this transformation. However, this loader only seems to process my own less files and not the files that are referenced in @import statements (seems like loaders are not called recursively). Any idea how to deal with this? For now, I'm just using a custom sed step to pre-process all less files before calling webpack.

Loader is broken

Please see the comment I left here: b40acff

Note that I had other errors while running this loader, but resultcs being undefined was the first error.

Problem with font-awesome

Here is the errors:

ERROR in ./~/font-awesome/fonts/fontawesome-webfont.woff2?v=4.4.0
Module parse failed: C:\OpenServer\domains\react-hot-boilerplate\node_modules\font-awesome\fonts\fontawesome-webfont.woff2?v=4.4.0 Line 1: Unexpected token ILLEGAL
You may need an appropriate loader to handle this file type.
(Source code omitted for this binary file)
 @ ./~/css-loader!./~/less-loader!./src/_styles/styles.less 6:92564-92646

ERROR in ./~/font-awesome/fonts/fontawesome-webfont.woff?v=4.4.0
Module parse failed: C:\OpenServer\domains\react-hot-boilerplate\node_modules\font-awesome\fonts\fontawesome-webfont.woff?v=4.4.0 Line 1: Unexpected token ILLEGAL
You may need an appropriate loader to handle this file type.
(Source code omitted for this binary file)
 @ ./~/css-loader!./~/less-loader!./src/_styles/styles.less 6:92677-92758

Here is my conf

var path = require('path');
var webpack = require('webpack');

module.exports = {
    devtool: 'eval',
    entry: [
        'webpack-dev-server/client?http://localhost:3000',
        'webpack/hot/only-dev-server',
        './src/index'
    ],
    output: {
        path: path.join(__dirname, 'dist'),
        filename: 'bundle.js',
        publicPath: '/static/'
    },
    plugins: [
        new webpack.HotModuleReplacementPlugin()
    ],
    module: {
        loaders: [{
            test: /\.js$/,
            loaders: ['react-hot', 'babel'],
            include: path.join(__dirname, 'src')
        }, {
            test: /\.less$/,
            loader: 'style!css!less'
        }, {
            test: /\.(jpe?g|gif|png|eot|svg|woff2|ttf)$/,
            loader: 'file'
        }]
    }
};

any suggestions? Maybe I need some preLoader?

data-uri doesn't work

@jhnns, @sokra one again, it doesn't work, background-image: data-uri('../img/privateinvestocat.jpg');

lessc compiles correctly, but less-loader outputs corrupted image.

Here is data-uri.less:

.data-uri {
  background-image: data-uri('../img/privateinvestocat.jpg');
}

Where ../img/privateinvestocat.jpg is https://octodex.github.com/images/privateinvestocat.jpg

lessc --no-ie-compat test/less/data-uri.less test/less/data-uri.css outputs:

.data-uri {
  background-image: url("data:image/jpeg;base64,/9j/4QAYRXhpZgAASUkqAAgAAAAAAAAAAAAAAP/sABFEdWNreQABAAQAAABkAAD/4QMxaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wLwA8P3hwYWNrZXQgYmVnaW49Iu+7vyIgaWQ9Ilc1TTBNcENlaGlIenJlU3pOVGN6a2M5ZCI/PiA8eDp4bXBtZXRhIHhtbG5zOng9ImFkb2JlOm5zOm1ldGEvIiB4OnhtcHRrPSJBZG9iZ...//Z");
}

but less-loader?ieCompat=false outputs:

.data-uri {
  background-image: url("data:image/jpeg;base64,77+977+977+977+9ABhFeGlmAABJSSoACAAAAAAAAAAAAAAA77+977+9ABFEdWNreQABAAQAAABkAADvv73vv70DMWh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC8APD94cGFja2V0IGJlZ2luPSLvu78iIGlkPSJXNU0wTXBDZWhpSHpyZVN6TlRjemtjOWQiPz4gPHg6eG1wbWV0YSB4bWxuczp4PSJhZG9iZTpuczptZXRhLyIgeDp4bXB0az0iQWRvYmUgWE1QIENvcmUgNS42LWMwMTQgNzkuMTU2Nzk3LCAyMDE0LzA4LzIwLTA5OjUzOjAyICAgICAgICvVJaSiPvv70L77+9dGjvv73vv73vv70k77+977+977+977+977+9biTvv73vv70S77+9RF0x77+9dO+/ve+/vdu7P++/vXLvv713Ee+/vSbvv73vv71/VWQbf2nvv70/Bxrvv73vv70ix4de77+9Je+/ve+/vTdz77+9aO+/ve+/vXHvv70uPR0TLe+/ve+/vULvv71Jbjbvv71NIceeW2zvv73jiZRy77+9c3Lvv73vv73vv70h77+977+9zY3vv73vv73vv70PU++/ve+/vWvvv73vv73vv71tCe+/ve+/vTNTRGbvv73elTrvv71w77+9Zu+/ve+/vQjvv71s77+977+977+9LUfvv73vv73vv71F77+9ce+/ve+/vWFnN17vv71d77+93rrvv71l77+9G++/vUU1H++/vXTvv73Gv++/ve+/vUFz77+9JQ3vv73vv70177+9RO+/ve+/ve+/ve+/vVHvv73vv73vv70477+977+977+9Uh7vv70cSe+/vV3vv71s77+9JXtNFjBbV++/ve+/vQXvv71e77+9J++/vQzvv73vv70gUzvvv70A77+9YnHvv73vv73vv70W77+9Rz7fk++/vW4r77+977+9Su+/vSrvv73vv70ReO+/ve+/ve+/ve+/ve+/AAAAPvv73vv70=");
}

Unable to build lesshat's .background-image mixin

Trying to build a LESS module using LESSHat via less-loader, but any encounter of .background-image() fails with:

ERROR in ./~/css-loader!./~/less-loader!./components/ux.less
Module build failed: JavaScript evaluation error: 'TypeError: Cannot read property 'length' of null'
 @ /my_path/Button.less (line 120, column 2)
 near lines:
    &-default {
        .background-image(linear-gradient(to bottom, @button-bg-start 0%, @button-bg-end 100%));
        border: 1px solid @button-border;
 @ ./components/ux.less 4:14-211

EDIT NON-ISSUE.

Font file "Module Parse Failed"

Attempting to compile a LESS file that references font-faces:

@font-face {
  font-family: 'Lato';
  font-style: normal;
  font-weight: 300;
  src: local('Lato Light'), local('Lato-Light'), url(fonts/lato/lato-light.woff) format('woff');
}
@font-face {
  font-family: 'Lato';
  font-style: normal;
  font-weight: 400;
  src: local('Lato Regular'), local('Lato-Regular'), url(fonts/lato/lato.woff) format('woff');
}
@font-face {
  font-family: 'Lato';
  font-style: normal;
  font-weight: 700;
  src: local('Lato Bold'), local('Lato-Bold'), url(fonts/lato/lato-bold.woff) format('woff');
}

Configuration:

{
  test: /\.less$/,
  loader: "style-loader!css-loader!less-loader"
}
ERROR in ./assets/css/fonts/lato/lato-light.woff
Module parse failed: /home/hekar/code/mobile/assets/css/fonts/lato/lato-light.woff Line 1: Unexpected token ILLEGAL
You may need an appropriate loader to handle this file type.
(Source code omitted for this binary file)
 @ ./~/css-loader!./~/less-loader?strictMath&cleancss!./assets/css/mobile.less 2:173-212

I assume webpack is attempting to process at all url(...) statements. Would there be a way to force the webpack or less-loader to ignore this url(...)?

ModuleBuildError: Module build failed: TypeError: Cannot read property 'rules' of undefined

Sometimes less dies because of this error

Error: Bundle creation failed due to Errors: 
ModuleBuildError: Module build failed: TypeError: Cannot read property 'rules' of undefined
    at Object.tree.Import.eval (/path/to/project/node_modules/less/lib/less/tree/import.js:115:56)
    at Object.tree.Ruleset.evalImports (/path/to/project/node_modules/less/lib/less/tree/ruleset.js:165:40)
    at Object.tree.Import.eval (/path/to/project/node_modules/less/lib/less/tree/import.js:117:21)
    at Object.tree.Ruleset.evalImports (/path/to/project/node_modules/less/lib/less/tree/ruleset.js:165:40)
    at Object.tree.Import.eval (/path/to/project/node_modules/less/lib/less/tree/import.js:117:21)
    at Object.tree.Ruleset.evalImports (/path/to/project/node_modules/less/lib/less/tree/ruleset.js:165:40)
    at Object.tree.Ruleset.eval (/path/to/project/node_modules/less/lib/less/tree/ruleset.js:73:21)
    at Object.toCSS (/path/to/project/node_modules/less/lib/less/parser.js:575:46)
    at /path/to/project/node_modules/less/lib/less/index.js:26:54
    at Object.finish [as _finish] (/path/to/project/node_modules/less/lib/less/parser.js:669:28)
    at Watching.handler (/path/to/project/server/createBundle.js:13:22)
    at Watching._done (/path/to/project/node_modules/webpack/lib/Compiler.js:77:7)
    at Watching.<anonymous> (/path/to/project/node_modules/webpack/lib/Compiler.js:57:18)
    at Tapable.emitRecords (/path/to/project/node_modules/webpack/lib/Compiler.js:263:37)
    at Watching.<anonymous> (/path/to/project/node_modules/webpack/lib/Compiler.js:54:19)
    at /path/to/project/node_modules/webpack/lib/Compiler.js:256:11
    at Tapable.applyPluginsAsync (/path/to/project/node_modules/webpack/node_modules/tapable/lib/Tapable.js:48:69)
    at Tapable.afterEmit (/path/to/project/node_modules/webpack/lib/Compiler.js:253:8)
    at Tapable.<anonymous> (/path/to/project/node_modules/webpack/lib/Compiler.js:248:14)
    at /path/to/project/node_modules/webpack/node_modules/async/lib/async.js:119:25

I don't have a clue why it happens and it might also be an issue with less, just for the record. It doesn't have to do with a special less syntax because the same module will sometimes trigger this error and sometimes not.

I couldn't find an issue at the less repo so I'm suspecting that a change within 087d523 might trigger it.

Optional ~ for modules

Why do I need to prepend ~ for modules? I'd rather prepend ./ for relative files. This seems to work great, when I comment this line: var moduleRequest = loaderUtils.urlToRequest(filename, query.root);

@import "module-foo/style.less"; // loads from my modules
@import "./module-bar.less"; // loads relative file

Can we make ~ optional?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.