You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将postcss.config.js的require语法改为ES6 import语法

问题原因
  • 你使用的import()是动态导入语法,返回值为Promise对象,并非实际导出的插件函数/实例,无法直接作为PostCSS插件调用,这是purgecss is not a function、插件无效报错的核心原因。
  • 配置文件后缀修改错误:.cjs是CommonJS模块的专属后缀,不会按ES模块规则解析,你需要的是ES模块配置,要么在package.json中新增"type": "module"字段直接用.js后缀,要么将配置文件后缀改为.mjs。
  • ES模块的导出语法错误,不能使用CommonJS的module.exports,需要替换为export default。
  • 部分基于CommonJS编写的PostCSS插件,使用ES模块导入时默认导出会挂载在default属性下,需要特殊处理。
正确配置示例

如果已经在package.json设置了"type": "module",直接用如下postcss.config.js即可,tailwind配置文件保持.js后缀就行:

import tailwindcss from 'tailwindcss'
import autoprefixer from 'autoprefixer'
import cssnano from 'cssnano'
import purgecss from '@fullhuman/postcss-purgecss'
import discardComments from 'postcss-discard-comments'
import discardEmpty from 'postcss-discard-empty'

export default {
  plugins: [
    tailwindcss('./tailwind.config.js'),
    process.env.NODE_ENV === 'production' ? autoprefixer : null,
    process.env.NODE_ENV === 'production' ? cssnano({ preset: 'default' }) : null,
    discardComments(),
    discardEmpty(),
    purgecss({
      content: ['./dev/**/*.html', './src/**/*.ts'],
      defaultExtractor: content => content.match(/[\w-/:]+(?<!:)/g) || []
    })
  ]
}
兼容处理

如果运行后仍提示某个插件不是函数,说明该包的ES模块兼容需要显式取default属性,修改导入和调用方式即可,以purgecss为例:

// 修改导入写法
import * as purgecss from '@fullhuman/postcss-purgecss'
// 调用时取default属性
purgecss.default({
  // 原有配置
})

内容的提问来源于stack exchange,提问作者Marc Rasmussen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 08:54:02