You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用less-loader未链式调用css-loader时Webpack报解析错误,求指导

Hey there, let's break this down step by step for your webpack 4.5.0 setup.

Less-loader运行机制(Webpack 4.5.0)

First, let's clarify what each part does and how they work together:

  • less-loader的核心作用:它专门负责把你写的Less代码(包含变量、嵌套、混合等Less特有语法)编译转换成标准的CSS代码。但它只做这一件事——编译Less到CSS,仅此而已。
  • 为什么需要css-loader配合:Webpack本身只能原生解析JS和JSON文件,它完全不认识CSS代码的语法(比如大括号、冒号这些)。所以less-loader输出的CSS代码,Webpack还是没法处理,这时候css-loader就派上用场了:
    • css-loader会把CSS代码转换成Webpack能识别的模块格式,处理CSS里的@import引用和url()资源路径,还能支持模块化CSS的特性。
  • Loader执行顺序:Webpack里的loader是从右到左(或者说数组里从后往前)执行的。所以处理Less文件时,必须把less-loader放在css-loader的后面(数组里的顺序是['css-loader', 'less-loader'])——这样Webpack会先让less-loader编译Less到CSS,再让css-loader处理这个CSS产物。
解决"Module parse failed: Unexpected token"错误

That error pops up exactly because you're using less-loader alone without chaining css-loader. Here's why:
When you only use less-loader, it compiles your Less to CSS, but then Webpack tries to parse that CSS code as if it were JS. Since CSS syntax (like {, :, }) isn't valid JS in that context, Webpack throws the "Unexpected token" error.

To fix this, you need to update your module rules with the correct chained loaders for .less files. Here's the complete rule you should add:

{
    test: /\.less$/,
    use: [
        // Optional: Add 'style-loader' here if you want to inject CSS into the page via <style> tags
        // 'style-loader',
        'css-loader',
        'less-loader'
    ]
}

If you want the compiled CSS to be injected directly into your HTML's <style> tags (instead of just being bundled as a module), uncomment the style-loader line.

Quick Recap
  • less-loader = Less → CSS compilation only
  • css-loader = makes CSS understandable to Webpack
  • Always chain them in the right order for Webpack 4 to process Less files correctly.

内容的提问来源于stack exchange,提问作者Bruce Sun

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 06:42:24