van*_*ert 7 css sass webpack postcss
Webpack / PostCSS无法处理具有内联注释的.pcss文件:
模块构建失败:语法错误
Run Code Online (Sandbox Code Playgroud)(77:5) Unknown word > 77 | // } | ^
我的Webpack配置的PostCSS部分:
let PostCSSConfig = {
sourceMap: true,
plugins: () => [
require('postcss-smart-import'),
require('precss')({}),
require('postcss-for')({}),
require('postcss-mixins')({}),
require('postcss-math')({}),
require('postcss-percentage')({}),
require('postcss-flexbugs-fixes')({}),
require('postcss-cssnext')({browsers: ['> 0.05%', 'IE 7'], cascade: false})
]
};
Run Code Online (Sandbox Code Playgroud)
config.module.rules:
{
test: /\.pcss$/,
exclude: inlineCSS,
use: ExtractTextPlugin.extract({
use: [{
loader: 'css-loader',
options: {
sourceMap: true
}
},
{
loader: 'postcss-loader',
options: PostCSSConfig
}
]
})
}
Run Code Online (Sandbox Code Playgroud)
我尝试使用以下插件:
但没有帮助,我每次都会出错。
atw*_*147 10
你提到postcss-comment,显然,postcss-comment不是一个 PostCSS 插件,它是一个解析器。
在我自己的项目中,我使用了一个 PostCSS 配置文件,如下所示:
// postcss.config.js
module.exports = () => ({
plugins: {
'postcss-import': {},
'postcss-cssnext': {},
'cssnano': {},
}
});
Run Code Online (Sandbox Code Playgroud)
安装您选择的解析器:
npm i -D postcss-comment`
Run Code Online (Sandbox Code Playgroud)
然后将以下行添加到您的配置中:
parser: require('postcss-comment'),
Run Code Online (Sandbox Code Playgroud)
那应该工作。
您的最终配置将如下所示:
module.exports = () => ({
parser: require('postcss-comment'),
plugins: {
'postcss-import': {},
'postcss-cssnext': {},
'cssnano': {},
}
});
Run Code Online (Sandbox Code Playgroud)
我的关键是找到这个 Github 问题:https : //github.com/postcss/postcss-scss/issues/58#issuecomment-318464851
内联注释(像这样:)// I'm a comment!是无效的 CSS。但它们是有效的 SCSS,因此如果您想在.css文件中使用它们,则需要使用带有 PostCSS 的 SCSS 解析器来转换这些文件。PostCSS SCSS可以做到这一点。要使用它,请将其设置为 PostCSS 的解析器。这是一个 webpack 配置示例:
// webpack.config.js
const path = require("path");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
module.exports = {
entry: path.resolve(__dirname, "main.js"),
output: {
path: path.resolve(__dirname, "dist"),
filename: "main.js"
},
plugins: [
new MiniCssExtractPlugin({
filename: "[name].css",
chunkFilename: "[id].css"
})
],
module: {
rules: [
{
test: /\.css$/,
use: [
{
loader: MiniCssExtractPlugin.loader
},
{ loader: "css-loader" },
// Set postcss-scss as the parser, allowing valid SCSS syntax
{ loader: "postcss-loader", options: { parser: "postcss-scss" } }
]
}
]
}
};
Run Code Online (Sandbox Code Playgroud)
这将转换以下 CSS:
// I am an inline comment!
// I'm invalid CSS, but I'll be transformed into a valid block comment.
body {
background-color: gold;
}
Run Code Online (Sandbox Code Playgroud)
进入这个:
/* I am an inline comment!*/
/* I'm invalid CSS, but I'll be transformed into a valid block comment.*/
body {
background-color: gold;
}
Run Code Online (Sandbox Code Playgroud)
这是一个有效的 CodeSandbox 示例:https ://codesandbox.io/s/kxqv1xvlx5