next.js如何同时支持导入css和less

next.js 从9.2版本开始内置支持css,项目中可以直接导入css文件。想要同时支持导入less,需要手动安装@zeit/next-less,在项目根目录新建文件next.config.js,添加如下代码

1
2
const withLess = require('@zeit/next-less')
module.exports = withLess()

这样做虽然支持导入less文件,但禁用了默认的css支持。重启应用,你就会看到一个警告

Built-in CSS support is being disabled due to custom CSS configuration being detected.

当你再导入css文件时,会收到如下报错

Module parse failed: Unexpected token
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders

错误提示的意思很明确,需要一个处理器对css文件进行处理。
解决这个问题并不困难,手动安装@zeit/next-css,然后修改next.config.js为以下内容

1
2
3
const withLess = require('@zeit/next-less')
const withCss = require('@zeit/next-css')
module.exports = withCss(withLess())

重启应用,这时候就同时支持导入css和less。

优惠福利

江山父老能容我,不使人间造孽钱