使用条目使用Less和MiniCssExtractPlugin的Webpack 4

时间:2018-08-03 11:16:52

标签: webpack less webpack-style-loader webpack-4 mini-css-extract-plugin

我的应用程序具有以下样式结构:

应用

- css/
   - bootstrap/
      - boostrap.less -> has (@import "another.less")
      - another.less
   - common/
      - common.less
   - entries/
      - bootstrap.js -> has (import style from "../bootstrap/bootstrap.less")
      - common.js -> has (import common from "../common/common.less")

现在,我需要从导入到条目bootstrap.js和common.js的样式中创建单独的CSS-es。

webpack.config.js

const MiniCssExtractPlugin = require("mini-css-extract-plugin");
{
    entry: {
        "boostrap": ["./css/entries/boostrap.js"]
    },
    module: {
        rules: [
            {
                test: /\.(less)$/,
                use: [
                    MiniCssExtractPlugin.loader,
                    "css-loader",
                    "less-loader"
                ]
            }
        ]
    },
    plugins: [
        new MiniCssExtractPlugin({
            filename: "./css/[name].css"
        })
    ]
}

package.json

{
    "webpack": "^4.16.3",
    "webpack-cli": "^3.1.0",
    "css-loader": "^1.0.0",
    "less-loader": "^4.1.0",
    "mini-css-extract-plugin": "^0.4.1",
}

当我运行webpack时,出现以下错误:

Entrypoint boostrap = boostrap.js
    [0] multi ./css/entries/boostrap.js 28 bytes {0} [built]
    [1] ./css/entries/boostrap.js 48 bytes {0} [built]
    [2] ./css/bootstrap/bootstrap.less 1.41 KiB {0} [built] [failed] [1 error]

    ERROR in ./css/bootstrap/bootstrap.less
    Module build failed (from ./node_modules/mini-css-extract-plugin/dist/loader.js):
    ModuleParseError: Module parse failed: Unexpected character ' ' (1:0)
    You may need an appropriate loader to handle this file type.

您有什么问题吗?好像bootstrap.less在导入其他较少文件时抛出错误,但我不知道为什么。

谢谢

Rafal

PS:报告了类似的问题here

1 个答案:

答案 0 :(得分:3)

我找到了原因。原来我的boostrap.less引用了glyphicons.less。 Glyphicons导入用于扩展的字体:* .eot,*。woff2,*。woff,*。ttf和* .svg,这是我缺少的部分。

我必须添加file-loader包裹

  

npm安装网址加载程序--save-dev

并添加如下配置:

const MiniCssExtractPlugin = require("mini-css-extract-plugin");
{
    entry: {
        "boostrap": ["./css/entries/boostrap.js"]
    },
    module: {
        rules: [
            {
                test: /\.(less)$/,
                use: [
                    MiniCssExtractPlugin.loader,
                    "css-loader",
                    "less-loader"
                ]
            },
            {
                test: /\.woff($|\?)|\.woff2($|\?)|\.ttf($|\?)|\.eot($|\?)|\.svg($|\?)/,
                use: "url-loader"
            }
        ]
    },
    plugins: [
        new MiniCssExtractPlugin({
            filename: "./css/[name].css"
        })
    ]
}

谢谢

Rafal