我正在使用Webpack4。
我的webpack.config.js
中有两个入口点,每个入口点都使用mini-css-extract-plugin
生成一个单独的CSS文件。
const webpack = require('webpack')
const path = require('path')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
module.exports = {
mode: 'development',
entry: {
foo: './foo.js',
bar: './bar.js'
},
output: {
path: path.resolve(__dirname, 'src/'),
filename: 'js/[name].js'
},
plugins: [
new MiniCssExtractPlugin({
filename: "css/[name].css"
})
],
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
}
},
{
test: /\.css$/,
use: [
{
loader: MiniCssExtractPlugin.loader
},
"css-loader", "postcss-loader"
]
}
]
}
}
我也在使用postcss-cssnext。
在根文件夹的postcss.config.js
文件中,我正在customProperties
中定义许多CSS变量,如下所示:
module.exports = {
plugins: {
'postcss-cssnext': {
features: {
customProperties: {
variables: {
color1: '#333',
color2: '#53565A',
baseFont: 'Helvetica, sans-serif'
}
}
}
}
}
}
如果我希望我的CSS变量的两个入口点都具有不同的值,那我该怎么做?
例如,假设在foo.css中我希望var(--color1)
等于#333
,但是在bar.css中我希望其等于#860000
。
答案 0 :(得分:1)
我知道了。这是我解决的方法。
我将webpack.config文件切换为具有多个配置,每个入口点一个。我还配置了postcss-loader,以将入口点作为上下文传递给postcss.config.js。
webpack.config.js
const webpack = require('webpack')
const path = require('path')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const entryPoints = ['foo', 'bar']
const config = entry => ({
mode: 'development',
entry: `./${entry}.js`,
output: {
path: path.resolve(__dirname, 'src/'),
filename: `js/${entry}.js`
},
plugins: [
new MiniCssExtractPlugin({
filename: `css/${entry}.css`
})
],
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader'
}
},
{
test: /\.css$/,
use: [
{
loader: MiniCssExtractPlugin.loader
},
'css-loader',
{
loader: 'postcss-loader',
options: {
config: {
ctx: { entry }
}
}
},
]
}
]
}
})
module.exports = entryPoints.map(entry => config(entry))
然后可以基于入口点有条件地配置我的postcss.config.js文件。在此示例中,我定义了内联样式,但是可以通过require
从外部模块中提取样式。
postcss.config.js
module.exports = ({ options }) => ({
plugins: {
'postcss-cssnext': {
features: {
customProperties: {
variables:
options.entry === 'foo' ?
{
color1: '#333',
color2: '#53565A',
baseFont: 'Helvetica, sans-serif'
} :
{
color1: '#860000',
color2: '#555',
baseFont: 'Arial, sans-serif'
}
}
}
}
}
})
答案 1 :(得分:0)
您也可以在postcss.config.js中尝试 env.file.basename :
pg-promise