Webpack Less-Loader with Style-Loader not injectin

2019-08-20 03:34发布

问题:

I'm trying to have our .less files picked up by less-loader, then by css-loader, and finally injected into the HTML file by style-loader, as per the Less Loader docs.

I am not getting any errors or warnings, but the styles are not injected or present in any way.

My webpack config is as follows, under module.rules[]...:

{
     test: /\.css$/,
         use: ['style-loader', 'css-loader']
     },
     {
        test: /\.less$/,
        use: [{
                loader: "style-loader" // creates style nodes from JS strings
        }, {
                loader: "css-loader" // translates CSS into CommonJS
        }, {
                loader: "less-loader",
                // options: {
                //     paths: [
                //         path.resolve(__dirname, '../less')
                //     ]
                // } // compiles Less to CSS
       }]
    },
}

My resolve is as follows

resolve: {
    extensions: ['.js', '.vue', '.json', '.less'],
    alias: {
        '@': resolve('public/js'),
    },
    modules: ['less', 'node_modules']
},

I have also tried, under modules, path.resolve(__dirname, '../less')

My directory structure is

project/build/webpack.config.js

project/less/*.less (less files)

I have also tried with the commented "options" above uncommented, to point directly at the less directory, as per the less-loader docs.

What am I missing to have these less styles compiled to CSS and injected as a style tag?

I included the .css test because I'm curious if maybe there's some sort of conflict happening there. It's being used to inject the bootstrap css file from node_modules, which is working properly.

(I tried to keep the code brief and only including relevant portions - happy to provide more)

回答1:

You need to import your .less files in your .js files in this way webpack loader will find them and make it work.

Here I have a repo with some configuration and I think it will help you with some issues that you'll face later. (Yeah it becomes a little bit wilder)

Regards.