使用 Less 和 MiniCssExtractPlugin 的 Webpack 4 条目

Webpack 4 with Less and MiniCssExtractPlugin using entries

我的应用程序中的样式结构如下:

申请

- 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 在 import other less file 期间抛出错误,但我不知道为什么。

谢谢

拉法尔

PS:已报告类似问题 here

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

file-loaderurl-loader 是两个可能的选项。我选择了后者:

npm install url-loader --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"
        })
    ]
}

谢谢

拉法尔