首页 分类
阿荡的博客

next.js与antd-mobile:定制主题和按需引入的报错和解决

创建时间:2020-11-25

更新时间:1 分钟前

注意

该方法只适合 nextjs10 版本

关于定制主题和按需引入,antd-mobile 官方文档给出了明确的方案, 在实际使用过程中遇到一些报错。这个文章记录了这些报错,以及一些解决方案。

关于按需加载,官方文档是 https://antd-mobile.gitee.io/docs/react/introduce-cn#%E6%8C%89%E9%9C%80%E5%8A%A0%E8%BD%BD (opens new window)

根据官方的建议新建.babelrc 文件,添加如下代码

{
    "presets": [
        "next/babel"
    ],
    "plugins": [
        [
            "import",
            {
                "libraryName": "antd-mobile",
                "style": "css"
            }
        ] // `style: true` 会加载 less 文件
    ]
}

重启项目,报错:

警告

/Users/**/node_modules/_normalize.css@7.0.0@normalize.css/normalize.css:12

html {

^

SyntaxError: Unexpected token {

原因分析:在服务端,@zeit/next-css 插件不会正确处理 node_modules 目录下的 css 文件。

解决方案:在服务端,针对 antd-mobile 相关的样式文件,用 null-loader 进行处理。

在 next.config.js 的 webpack 配置中添加如下代码,记得先手动安装 null-loader

webpack(config, {isServer}) {
    if (isServer) {
        const antStyles = /antd-mobile\/.*?\/style.*?/const origExternals = [...config.externals] config.externals = [(context, request, callback) = >{
            if (request.match(antStyles)) return callback() if (typeof origExternals[0] === 'function') {
                origExternals[0](context, request, callback)
            } else {
                callback()
            }
        },
        ... (typeof origExternals[0] === 'function' ? [] : origExternals), ]

        config.module.rules.unshift({
            test: antStyles,
            use: 'null-loader',
        })
    }
    return config
}

关于定制主题,官方文档为 https://antd-mobile.gitee.io/docs/react/customize-theme-cn 需要把上面的 "style": "css" 改为 "style": true 。 此外,官方提供的 webpack 修改方式不适合 next.js,应该在 next.config.js 中的 webpack 新增以下配置:

config.module.rules.push({
  test: /\.less$/,
  use: [
    "postcss-loader",
    {
      loader: "less-loader",
      options: { modifyVars: theme, javascriptEnabled: true },
    },
  ],
});