错误来自 webpack-spritesmith 插件生成的 LESS 文件:
ERROR in ./assets/less/main.less
Module build failed (from ./node_modules/mini-css-extract-plugin/dist/loader.js):
ModuleBuildError: Module build failed (from ./node_modules/less-loader/dist/cjs.js):
@spritesheet-sprites:;
@spritesheet: 0px 0px '~img/generated/sprite.png' @spritesheet-sprites;
Cannot read property 'eval' of null
出于某种原因,该spritesheet-sprites
变量似乎是在没有值的情况下定义的。在我将 Webpack 版本从 1.13 升级到 5.22(连同它的加载器)后,我遇到了这个错误。我尝试降级一些依赖项,例如 less、less-loader 和 webpack-spritesmith 插件本身,但似乎没有用。还检查了较新版本的 Webpack 及其加载器是否以不同的方式处理路径,没有结果。
我按照他们的官方文档编写了配置(用于 webpack 和插件),一切似乎都已到位,但通过在线检查资源,我找不到我的配置是否错误或包中是否存在不匹配的版本。
我的 webpack 配置:
const path = require('path');
const webpack = require('webpack');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const SpritesmithPlugin = require('webpack-spritesmith');
const mainPath = path.join(__dirname, './assets');
module.exports = {
mode: 'production',
stats: 'verbose',
resolve: {
extensions: ['.js'],
alias: {
assets: mainPath,
js: path.join(mainPath, 'js'),
less: path.join(mainPath, 'less'),
img: path.join(mainPath, 'img'),
fonts: path.join(mainPath, 'fonts')
},
},
entry: ['./assets/index'],
output: {
path: path.join(__dirname, 'dist'),
filename: '[name].js',
publicPath: './',
chunkFilename: '[id].[chunkhash].js'
},
module: {
rules: [
{
test: /\.js?/,
exclude: /(node_modules)/,
include: path.join(__dirname, 'assets'),
use: ['babel-loader']
},
{
test: /\.(ttf|eot|svg|woff|woff2)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
use: ['file-loader']
},
{
test: /\.jpe?g$|\.gif$|\.png$/i,
use: ['file-loader']
},
{
test: /\.less$/,
use: [MiniCssExtractPlugin.loader, 'style-loader', 'css-loader', 'less-loader'],
},
],
},
plugins: [
new SpritesmithPlugin({
src: {
cwd: path.resolve(__dirname, 'assets/img/sprite'),
glob: '*.png'
},
target: {
image: path.resolve(__dirname, 'assets/img/generated/sprite.png'),
css: path.resolve(__dirname, 'assets/less/generated/sprite.less')
},
apiOptions: {
cssImageRef: "~img/generated/sprite.png",
generateSpriteName: function(filePath) {
return 'sprite-' + path.basename(filePath, '.png');
}
}
}),
new MiniCssExtractPlugin({filename: 'style.css'})
]
};
包.json:
"devDependencies": {
"@babel/core": "^7.12.16",
"@babel/preset-env": "^7.12.16",
"babel-eslint": "7.0.0",
"babel-loader": "^8.2.2",
"cross-env": "3.0.0",
"css-loader": "^5.0.2",
"eslint": "3.7.0",
"eslint-plugin-babel": "3.3.0",
"eslint-plugin-react": "6.3.0",
"file-loader": "^6.2.0",
"less": "^3.0.0",
"less-loader": "^8.0.0",
"mini-css-extract-plugin": "^1.3.7",
"rimraf": "2.5.4",
"style-loader": "^2.0.0",
"unused-files-webpack-plugin": "^3.4.0",
"webpack": "^5.22.0",
"webpack-cli": "^4.5.0",
"webpack-dev-middleware": "1.8.3",
"webpack-hot-middleware": "2.12.2",
"webpack-spritesmith": "^1.1.0"
}