NextJs 构建失败,而开发服务器运行良好

NextJs build fails, while development server runs fine

我有一个自定义较少配置的 NextJs 应用程序:

const withSass = require("@zeit/next-sass");
const withLess = require("@zeit/next-less");
const withCSS = require("@zeit/next-css");

const isProd = process.env.NODE_ENV === "production";
const basePath = process.env.BASE_PATH || '';

// fix: prevents error when .less files are required by node
if (typeof require !== "undefined") {
  require.extensions[".less"] = (file) => {};
}

module.exports = withCSS({
  // basePath: basePath,
  cssModules: true,
  cssLoaderOptions: {
    importLoaders: 1,
    localIdentName: "[local]___[hash:base64:5]",
  },
  ...withLess(
    withSass({
      lessLoaderOptions: {
        javascriptEnabled: true,
      },
    })
  ),
});

运行 使用 npm run dev 的开发构建工作正常,而 运行 npm run build 导致以下错误:

./src/pages\index.tsx:2:20
Type error: Cannot find module '../../styles/Home.module.less' or its corresponding type declarations.

  1 | import Head from 'next/head'
> 2 | import styles from '../../styles/Home.module.less'
    |                    ^
  3 | import PageLayout from './layout'
  4 | 
  5 | export default function Home(props) {
info  - Creating an optimized production build .

这是什么原因?

正如评论所建议的那样,缺少 Typescript 编译器的声明:

///declaration.d.ts
declare module '*.less' {
    const resource: { [key: string]: string };
    export = resource;
}

和tsconfig.json中的相应参考:

"include": [
    "node_modules/@types",
    "next-env.d.ts",
    "declaration.d.ts",
    "**/*.ts",
    "**/*.tsx"
  ],