How to import LESS files from a specific path using webpack less-loader?

I am creating a reaction project together using webpack and LESS for styling. I use the component style structure as follows:

/root /src /components /MyComponent -index.js -index.less /styles -colors.less 

I want each component to reference its own styles using import:

 //MyComponent.js import React from 'react'; import styles from './index.less'; ... <div className={styles.someclass} > ... 

Inside index.less, I want to import common generic styles. Sort of:

 //index.less @import "styles/colors.js"; .someclass { background: @themecolor; } 

Here's how I installed webpack.config files for less:

  resolve: { alias: { components: path.resolve(__dirname, 'src', 'components'), reducers: path.resolve(__dirname, 'src', 'reducers'), actions: path.resolve(__dirname, 'src', 'actions'), styles: path.resolve(__dirname, 'src', 'styles'), images: path.resolve(__dirname, 'src', 'images'), pages: path.resolve(__dirname, 'src', 'pages'), lib: path.resolve(__dirname, 'src', 'lib'), utils: path.resolve(__dirname, 'src', 'utils'), examples: path.resolve(__dirname, 'src', 'examples') }, extensions: ['', '.js','.jsx', '.css', 'png', 'less'] }, module: { loaders: [ { test: /\.jsx$/, loader: 'babel', include: path.join(__dirname, 'src') }, { test: /\.js$/, loader: 'babel', exclude: /node_modules/ }, { test: /\.css$/, loader: "css-loader!autoprefixer-loader" }, { test: /\.less$/, loader: "style!css!autoprefixer!less" }, { test: /\.png$/, loader: "url-loader?limit=10000&minetype=image/jpg" } ] }, ... 

As you can see, I use Webpack's alias resolution feature extensively, so I don’t have to worry about relative paths everywhere.

The problem is that I cannot import styles. I have tried every method based on google search, including:

 @import "~styles/colors.less"; //not sure what the ~ does? @import "/styles/colors.less"; @import "styles/colors.less"; @import "../../styles/colors.less"; 

Either it compiles, but the styles are not displayed, or I get an error that the file could not be resolved.

Is there a way to get webpack to solve these problems using aliases? I really don't want to figure out the relative path here, if I can avoid it, because my nest will be deep enough. I will, if necessary, though, to make it work.

How can I do it?

+5
source share
1 answer

~ is a convenience for downloading less files from the node_modules folder for webpack less-loader . check https://github.com/webpack-contrib/less-loader#imports

0
source

All Articles