Webpack2 loading and extracting LESS file

限于喜欢 提交于 2019-12-22 09:46:56

问题


I am trying to setup Webpack2 to process my LESS files and create a separate CSS from it. I keep getting an error however. I've had trouble locating Webpack2 examples outlining the process so not sure what I am missing.

My Webpack config:

module.exports = {
  entry: {
    'public': [
      './src/client/styles/public.js'
    ]
  },
  output: {
   ...
  },
  module: {
      {
       test: /.*\.less$/,
        loader: ExtractTextPlugin.extract({ loader: 'less-loader', fallbackLoader: 'style-loader' })
      }
    ]

  },
  plugins: [
    new ExtractTextPlugin({ filename: '[name].css', disable: false, allChunks: true })
  ]
}

The public.js file (I also tried passing the less file directly to entry with same result):

require('style.less')

The style.less file

a { color: red; }

The Error:

ERROR in ./~/less-loader!./src/client/styles/style.less
Module parse failed: /node_modules/less-loader/index.js!/src/client/styles/style.less Unexpected token (1:2)
You may need an appropriate loader to handle this file type.
| a {
|   color: red;
| }

It appears from the message that the less loader is correctly being passed the file but breaks. I've tried a blank file but then I get:

TypeError: text.forEach is not a function

Versions:

"extract-text-webpack-plugin": "^2.0.0-beta.4",
"less": "^2.7.1",
"less-loader": "^2.2.3",
"style-loader": "^0.13.1",
"webpack": "^2.1.0-beta.25",
"webpack-dev-server": "^2.1.0-beta.5",
"yargs": "~3.5.4"

What could be the issue?


回答1:


Ok.. got it working with:

 loader: ExtractTextPlugin.extract({ 
     loader:[ 'css', 'less' ], 
     fallbackLoader: 'style-loader' 
 })

Edit This was for Webpack v2 - thanks to @thelastshadow for note on Webpack 4 issue here.




回答2:


You perhaps also need to use an additional load like the style- or css-loaders. From the Docs:

var css = require("!raw!less!./file.less");
// => returns compiled css code from file.less, resolves imports
var css = require("!css!less!./file.less");
// => returns compiled css code from file.less, resolves imports and url(...)s

The less-loader just handles the processing into CSS. Webpack then needs to know how to incorporate the CSS before it's extracted back out.



来源:https://stackoverflow.com/questions/39666983/webpack2-loading-and-extracting-less-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!