首页 分类
阿荡的博客

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

创建时间:2020-11-25

更新时间:1 分钟前

注意

该方法只适合 nextjs10 版本

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

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 为以下内容

const withLess = require("@zeit/next-less");
const withCss = require("@zeit/next-css");
module.exports = withCss(withLess());

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