使用postcss-px-to-viewport适配时,网上搜的大多都是这种,但我运行后,发现根本找不到file,请问这是什么原因呢?
const path = require("path");
module.exports = ({ file }) => {
const designWidth = file.includes(path.join("node_modules", "vant")) ? 375 : 750;
return {
plugins: {
autoprefixer: {},
"postcss-px-to-viewport": {
unitToConvert: "px",
viewportWidth: designWidth,
unitPrecision: 6,
propList: ["*"],
viewportUnit: "vw",
fontViewportUnit: "vw",
selectorBlackList: [],
minPixelValue: 1,
mediaQuery: true,
exclude: [],
landscape: false,
},
},
};
};
[vite:css] Failed to load PostCSS config (searchPath: /Users/xxxxx/coding/xxx): [TypeError] Cannot read property 'includes' of undefined
这个报错提示说是无法读取 undefined 的 includes 属性,而 includes 是一个字符串的方法,因此可以初步判断 file 的值不是一个字符串。
根据代码,可以看到这里的 file 是一个参数,它的值是从哪里传入的呢?根据 Vite 的文档,可以了解到 Vite 的插件 API 中有一个 configureServer 方法,它可以用来配置服务器,其中可以传入一个参数 app,这个 app 对象中包含了当前请求的相关信息,其中就包括了 file。
因此,可以在 configureServer 方法中检查一下 app 对象是否包含了 file 属性,如果没有,则给它一个默认值,例如一个空字符串。
const path = require("path");
module.exports = ({ file = "" }) => {
const designWidth = file.includes(path.join("node_modules", "vant")) ? 375 : 750;
return {
plugins: {
autoprefixer: {},
"postcss-px-to-viewport": {
unitToConvert: "px",
viewportWidth: designWidth,
unitPrecision: 6,
propList: ["*"],
viewportUnit: "vw",
fontViewportUnit: "vw",
selectorBlackList: [],
minPixelValue: 1,
mediaQuery: true,
exclude: [],
landscape: false,
},
},
};
};