Giter Club home page Giter Club logo

next-plugin-antd-less's Introduction

Next.js + Antd (with Less)

version license size download

Use Antd (Less) w/ Next.js, Zero Dependency on other Next-Plugins.

Demo

Demo w/ Next.js v12 by mkn

Demo w/ CRA v5 by mkr

Yep! this plugin supports both Next.js and CRA since v1.0.

Features

  • Zero Dependency on other Next.js Plugins
  • Support Both Next.js & CRA Project
  • Support Hot-Update After modifying Antd less vars
  • Support Serverless Mode
  • Support Antd Pro

Compatibility

  • Next.js v11 / v12
  • CRA v4 / v5

Installation

yarn add next-plugin-antd-less
yarn add --dev babel-plugin-import

Usage

// next.config.js
const withAntdLess = require('next-plugin-antd-less');

module.exports = withAntdLess({
  modifyVars: { '@primary-color': '#04f' }, // optional
  lessVarsFilePath: './src/styles/variables.less', // optional 
  lessVarsFilePathAppendToEndOfContent: false, // optional
  // optional https://github.com/webpack-contrib/css-loader#object
  cssLoaderOptions: {
    // ... 
    mode: "local",
    localIdentName: __DEV__ ? "[local]--[hash:base64:4]" : "[hash:base64:8]", // invalid! for Unify getLocalIdent (Next.js / CRA), Cannot set it, but you can rewritten getLocalIdentFn
    exportLocalsConvention: "camelCase",
    exportOnlyLocals: false,
    // ...
    getLocalIdent: (context, localIdentName, localName, options) => {
      return "whatever_random_class_name";
    },
  },

  // for Next.js ONLY
  nextjs: {
    localIdentNameFollowDev: true, // default false, for easy to debug on PROD mode
  },

  // Other Config Here...

  webpack(config) {
    return config;
  },

  // ONLY for Next.js 10, if you use Next.js 11, delete this block
  future: {
    webpack5: true,
  },
});

Add a .babelrc.js

// .babelrc.js
module.exports = {
  presets: [['next/babel']],
  plugins: [['import', { libraryName: 'antd', style: true }]],
};

Detailed config can be found in next.config.js file.

for CRA / CRA-Co

const cracoPluginLess = require('next-plugin-antd-less/overrideWebpackConfig');

module.exports = {
  babel: cracoBabel,
  plugins: [
    cracoPluginAnalyze,
    {
      plugin: cracoPluginLess,
      options: {
        modifyVars: {
          '@THEME--DARK': 'theme-dark',
        },
        lessVarsFilePath: './src/styles/variables.less',
        cssLoaderOptions: {
          localIdentName: __DEV__ ? "[local]--[hash:base64:4]" : "[hash:base64:8]",
        },
      },
    },
  ],
};

Detailed config can be found in craco.config.js file.

FAQ

Reference Project?

If you have any problem, please check mkn (Next.js) and mkr (CRA) first, I update these two repo's every time I update this plugin.

Default ClassName

MODE className e.g.
DEV [local]--[hash:base64:4] comp-wrapper--2Rra
PROD [hash:base64:8] 2Rra8Ryx

for Unify getLocalIdent (Next.js / CRA), Cannot set it, but you can rewritten getLocalIdentFn

localIdentName is invalid? How to rewritten?

you can defind your own localIdentName in pluginOptions.cssLoaderOptions.modules.getLocalIdent

  options: {
  lessVarsFilePath: './src/styles/variables.less'
  // ...
  // https://github.com/webpack-contrib/css-loader/tree/b7a84414fb3f6e6ff413cbbb7004fa74a78da331#getlocalident
  //
  // and you can see file 
  // https://github.com/SolidZORO/next-plugin-antd-less/getCssModuleLocalIdent.js
  getLocalIdent: (context, _, exportName, options) => {
    return 'whatever_random_class_name';
  }
  // ...
}

How to import global CSS style (e.g. styles.css)?

// ./page/_app.tsx
//
// use `import` or `require` syntax,
import './styles.css';

How to import global Less style (e.g. styles.less)?

// ./page/_app.tsx
//
// use `require` syntax,
require('./styles.less');

How to overwrite antd less variables?

// ./src/styles/variables.less
@import '~antd/lib/style/themes/default.less'; // <-- you need to import antd variables once in your project

@primary-color: #04f; // change antd primary-color
// 🔰️ Tips: if your use babel import plugin and set `libraryDirectory`, please keep `libraryDirectory` and `less path` consistent.

// lib
['import', { libraryName: 'antd', libraryDirectory: 'lib', style: true }]
// `@import '~antd/lib/style/themes/default.less';` <-- use `lib`

// es
  ['import', { libraryName: 'antd', libraryDirectory: 'es', style: true }]
// --> `@import '~antd/es/style/themes/default.less';` <-- use `es`
// plugin options
lessVarsFilePath: './src/styles/variables.less'

@seeMore issues #36, #74

Background

Issues

Since Next.js 9.3 supports sass and css by default, but does not support less. If you use Next.js > 9.3 and use the official less plugin, you will definitely encounter the following problems.

  1. CIL Warning Warning: Built-in CSS support is being disabled due to custom CSS configuration being detected.

  2. Does not support automatic recognition of css modules, e.g. a.module.less and a.less

Solution

  1. Find sassModule and copy onec and replace the sass-loader inside with less-loader.

  2. Then enable the modules.auto option of css-loader. This can simply match all *.less (no need to match it is *.module.less or *.less), and hand it over to css-loader.

This is the lowest cost way, And CLI will no longer show this disgusting warning. The important thing is that there is Zero Dependency on other Next-Plugins..

License

MIT © Jason Feng

next-plugin-antd-less's People

Contributors

jernkuan avatar kir93 avatar nelsliu9121 avatar nring avatar richmonkeys avatar shian15810 avatar sitch avatar solidzoro avatar thornwu avatar veizz avatar zsevic avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

next-plugin-antd-less's Issues

antd theme customization broken with next-plugin-antd-less versions >= 1.0.0

Steps to reproduce:

  1. git clone https://github.com/rriski/next-plugin-antd-less
  2. yarn && yarn dev
  3. Table background is red and table header background is blue as specified in assets/antd-custom.less.
  4. Update next-plugin-antd-less to version 1.0.5.
  5. yarn && yarn dev
  6. Table background and header color are not changed from the default values.

The repo follows https://github.com/vercel/next.js/tree/canary/examples/with-ant-design-less with next-plugin-antd-less added. This plugin supported customizing the antd theme (https://ant.design/docs/react/customize-theme) prior to v1.0.0.

I suppose this commit is to blame: 418ec5c.

Cannot find module '/path/.next/fallback-build-manifest.json'

Hi there!

After I update the next.config.js and .babelrc.js
I got this message when running yarn dev command

Could you please help?

Error: Cannot find module '/Volumes/Data/projects/server/nextjs-admin/.next/fallback-build-manifest.json'
Require stack:
- /Volumes/Data/projects/server/nextjs-admin/node_modules/next/dist/next-server/server/load-components.js
- /Volumes/Data/projects/server/nextjs-admin/node_modules/next/dist/next-server/server/api-utils.js
- /Volumes/Data/projects/server/nextjs-admin/node_modules/next/dist/next-server/server/next-server.js
- /Volumes/Data/projects/server/nextjs-admin/node_modules/next/dist/server/next.js
- /Volumes/Data/projects/server/nextjs-admin/node_modules/next/dist/server/lib/start-server.js
- /Volumes/Data/projects/server/nextjs-admin/node_modules/next/dist/cli/next-dev.js
- /Volumes/Data/projects/server/nextjs-admin/node_modules/next/dist/bin/next
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:981:15)
    at Function.mod._resolveFilename (/Volumes/Data/projects/server/nextjs-admin/node_modules/next/dist/build/webpack/require-hook.js:4:1855)
    at Function.Module._load (internal/modules/cjs/loader.js:863:27)
    at Module.require (internal/modules/cjs/loader.js:1043:19)
    at require (internal/modules/cjs/helpers.js:77:18)
    at loadDefaultErrorComponents (/Volumes/Data/projects/server/nextjs-admin/node_modules/next/dist/next-server/server/load-components.js:1:652)
    at DevServer.renderErrorToHTML (/Volumes/Data/projects/server/nextjs-admin/node_modules/next/dist/next-server/server/next-server.js:139:962)
    at runMicrotasks (<anonymous>)
    at processTicksAndRejections (internal/process/task_queues.js:97:5)
    at async DevServer.render (/Volumes/Data/projects/server/nextjs-admin/node_modules/next/dist/next-server/server/next-server.js:75:160) {
  code: 'MODULE_NOT_FOUND',
  requireStack: [
    '/Volumes/Data/projects/server/nextjs-admin/node_modules/next/dist/next-server/server/load-components.js',
    '/Volumes/Data/projects/server/nextjs-admin/node_modules/next/dist/next-server/server/api-utils.js',
    '/Volumes/Data/projects/server/nextjs-admin/node_modules/next/dist/next-server/server/next-server.js',
    '/Volumes/Data/projects/server/nextjs-admin/node_modules/next/dist/server/next.js',
    '/Volumes/Data/projects/server/nextjs-admin/node_modules/next/dist/server/lib/start-server.js',
    '/Volumes/Data/projects/server/nextjs-admin/node_modules/next/dist/cli/next-dev.js',
    '/Volumes/Data/projects/server/nextjs-admin/node_modules/next/dist/bin/next'
  ]
}

This is my package.json

{
  "name": "nextjs-admin",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "lint": "next lint"
  },
  "dependencies": {
    "antd": "^4.16.3",
    "next": "11.0.0",
    "next-plugin-antd-less": "^1.3.0",
    "react": "17.0.2",
    "react-dom": "17.0.2"
  },
  "devDependencies": {
    "eslint": "7.28.0",
    "eslint-config-next": "11.0.0"
  }
}

How to import other .less files not from antd

Hi @SolidZORO , I have a problem I want to import other .less filess....
In development mode using this syntax, it works import './my-path/my-styles.less'
But when building the project these styles are not built and present in the build folder....also no errors appears.

Another interesting thing.....it works only when I'm using require('./my-path/my-styles.less').

So why it works with require but not with import?
And how to fix it??

Inline JavaScript is not enabled

HI

next-plugin-antd-less occurred in my environment

// https://github.com/ant-design/ant-motion/issues/44
.bezierEasingMixin();
^
Inline JavaScript is not enabled

package.json

"dependencies": {
    "@apollo/client": "^3.3.3",
    "antd": "^4.9.4",
    "deepmerge": "^4.2.2",
    "graphql": "^15.4.0",
    "next": "10.0.3",
    "react": "17.0.1",
    "react-dom": "17.0.1"
    "next-plugin-antd-less": "^0.1.4",
  },

Doesn't work with Antd 4.14+

I used the package with Antd 4.13.1
After upgrading to Antd 4.14+ (or Antd 4.15+), the customization stopped working.

I have the latest plugin release (v1.0.8)
And [email protected]

My less file :

// - Custom variables
@customer-color: #006FBA;
@customer-background-color: #FAFDFF;

// - Antd variables
@primary-color: @customer-color;
@link-color: @customer-color;
@heading-color: @customer-color;
@border-radius-base: 4px;
@layout-body-background: @customer-background-color;
@layout-sider-background: #FFFFFF;
@layout-header-background: #FFFFFF;
@layout-trigger-background: @customer-color;
@layout-header-color: @primary-color;
@alert-message-color: rgba(0, 0, 0, 0.85);

.ant-layout-header {
  border-bottom: 1px solid @primary-color;
}

My next.config.js file :

const withAntdLess = require('next-plugin-antd-less');

module.exports = withAntdLess({
  lessVarsFilePath: './styles/antd.less',
  cssLoaderOptions: { },
  i18n: {
    locales: ['en', 'fr'],
    defaultLocale: 'fr',
  },
});

Can't resolve less-loader

Cloning mkn works just fine, but trying to implement it into an existing project always results in:

wait  - compiling...
error - ./src/pages/_app.tsx:9:0
Module not found: Can't resolve 'less-loader'
   7 | import PageLayout from './layout'
   8 |
>  9 | require('@styles/globals.less')
  10 |
  11 | const MyApp = ({ Component, pageProps }: AppProps) => {

I've updated all installed modules, to be exactly the same as in the mkn demo, sans eslint and everything, that I don't use, but I just won't work.

"dependencies": {
      "@ant-design/icons": "^4.4.0",
      "@azure/msal-browser": "^2.14.0",
      "@azure/msal-react": "1.0.0-beta.1",
      "@babel/core": "^7.12.9",
      "@babel/preset-env": "^7.12.7",
      "@babel/preset-react": "^7.12.13",
      "@babel/preset-typescript": "^7.12.7",
      "@microsoft/microsoft-graph-client": "^2.1.1",
      "antd": "^4.16.3",
      "autoprefixer": "^10.2.6",
      "axios": "^0.21.1",
      "babel-jest": "^26.6.3",
      "css-loader": "^5.2.6",
      "babel-plugin-import": "^1.13.3",
      "babel-plugin-module-resolver": "^4.1.0",
      "classnames": "^2.3.1",
      "cookie": "^0.4.1",
      "cross-env": "^7.0.2",
      "jest": "^26.6.3",
      "lodash": "^4.17.21",
      "next": "11.0.0",
      "next-plugin-antd-less": "^1.3.0",
      "normalize.css": "^8.0.1",
      "react": "17.0.2",
      "react-dom": "17.0.2",
      "react-hook-form": "^6.15.4",
      "ts-jest": "^26.5.3"
   },
   "devDependencies": {
      "@testing-library/react": "^11.2.6",
      "@types/antd": "^1.0.0",
      "@types/classnames": "^2.3.1",
      "@types/cookie": "^0.4.0",
      "@types/jest": "22.2.3",
      "@types/microsoft-graph": "^1.26.0",
      "@types/node": "^14.14.7",
      "@types/react": "^17.0.11",
      "@types/react-dom": "^16.9.9",
      "jest-junit": "^12.0.0",
      "react-test-renderer": "^17.0.2",
      "@testing-library/jest-dom": "5.12.0",
      "@testing-library/user-event": "13.1.8",
      "typescript": "^4.3.2"
   }

If somebody could guide me in the right direction, that would be great.

Failed to use webpack 5 configuration on Next 11

Next.js 11 announced recently and it is making webpack 5 the default bundler. The future.webpack5 config in next.config.js has been moved to webpack5 and it is set to true by default. (see this)

To reproduce, go to this CodeSandbox

This is the error printed when running npm run dev:

(node:5223) [DEP_WEBPACK_EXTERNALS_FUNCTION_PARAMETERS] DeprecationWarning: The externals-function should be defined like ({context, request}, cb) => { ... }
(node:5223) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'startsWith' of undefined
    at handleExternals (/Users/nelsliu9121/Codes/next-plugin-antd-less-next11-reproduction/node_modules/next/dist/build/webpack-config.js:48:23)
    at Array.webpackConfig.externals._webpack.isWebpack5.require.resolve.paths (/Users/nelsliu9121/Codes/next-plugin-antd-less-next11-reproduction/node_modules/next/dist/build/webpack-config.js:87:77)
    at webpackConfig.externals (/Users/nelsliu9121/Codes/next-plugin-antd-less-next11-reproduction/node_modules/next-plugin-antd-less/overrideWebpackConfig.js:337:62)
    at /Users/nelsliu9121/Codes/next-plugin-antd-less-next11-reproduction/node_modules/next/dist/compiled/webpack/bundle5.js:53948:21
    at deprecated (internal/util.js:89:15)
    at handleExternals (/Users/nelsliu9121/Codes/next-plugin-antd-less-next11-reproduction/node_modules/next/dist/compiled/webpack/bundle5.js:54095:8)
    at next (/Users/nelsliu9121/Codes/next-plugin-antd-less-next11-reproduction/node_modules/next/dist/compiled/webpack/bundle5.js:54073:9)
    at handleExternals (/Users/nelsliu9121/Codes/next-plugin-antd-less-next11-reproduction/node_modules/next/dist/compiled/webpack/bundle5.js:54078:7)
    at /Users/nelsliu9121/Codes/next-plugin-antd-less-next11-reproduction/node_modules/next/dist/compiled/webpack/bundle5.js:54175:5
    at Hook.eval [as callAsync] (eval at create (/Users/nelsliu9121/Codes/next-plugin-antd-less-next11-reproduction/node_modules/next/dist/compiled/webpack/bundle5.js:31934:10), <anonymous>:35:1)

I need to config sass module regx

I need to config sass module regx, right now it is .module.(css) pattern, but I would like to pass an option to it (default remain the same)

I already create a PR for this thing.
[https://github.com//pull/48]

Does not work with webpack5 flag

webpack5 support is still in beta in nextjs. Looks like this plugin fails to load due to some internals changes.

const withAntdLess = require("next-plugin-antd-less");

module.exports = withAntdLess({
  future: {
    webpack5: true,
  },
});
(node:62355) [DEP_WEBPACK_EXTERNALS_FUNCTION_PARAMETERS] DeprecationWarning: The externals-function should be defined like ({context, request}, cb) => { ... }
(node:62355) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'startsWith' of undefined
    at handleExternals (<root>/node_modules/next/build/webpack-config.ts:609:15)
    at Array.webpackConfig.externals._webpack.isWebpack5.require.resolve.paths (<root>/node_modules/next/build/webpack-config.ts:755:21)
    at config.externals (<root>/node_modules/next-plugin-antd-less/index.js:146:24)
    at <root>/node_modules/next/dist/compiled/webpack/bundle5.js:48316:21

How to import component level less?

I'd like to use component level less import, how can I achieve that?
For example:

import styles from './header.module.less'

const Header = ({isMobile}) => {
  
  return (
    <Layout.Header className={styles.headerWrapper}>
      blabla
    </Layout.Header>
  )
}

useLayoutEffect next.js warning

I have this warning even I have try exact package document

Warning: useLayoutEffect does nothing on the server, because its effect cannot be encoded into the server renderer's output format. This will lead to a mismatch between the initial, non-hydrated UI and the intended UI. To avoid this, useLayoutEffect should only be used in components that render exclusively on the client. See https://reactjs.org/link/uselayouteffect-ssr for common fixes.
    at InputNumber (J:\JSKingdom\novel\novel-site\node_modules\rc-input-number\lib\InputNumber.js:59:32)
    at J:\JSKingdom\novel\novel-site\node_modules\antd\lib\input-number\index.js:46:33    at div
    at div
    at div
    at Col (J:\JSKingdom\novel\novel-site\node_modules\antd\lib\grid\col.js:57:33)    
    at FormItemInput (J:\JSKingdom\novel\novel-site\node_modules\antd\lib\form\FormItemInput.js:40:25)
    at div
    at Row (J:\JSKingdom\novel\novel-site\node_modules\antd\lib\grid\row.js:52:34)    
    at FormItem (J:\JSKingdom\novel\novel-site\node_modules\antd\lib\form\FormItem.js:89:20)
    at form
    at Form (J:\JSKingdom\novel\novel-site\node_modules\rc-field-form\lib\Form.js:31:19)
    at SizeContextProvider (J:\JSKingdom\novel\novel-site\node_modules\antd\lib\config-provider\SizeContext.js:15:23)
    at InternalForm (J:\JSKingdom\novel\novel-site\node_modules\antd\lib\form\Form.js:62:27)
    at div
    at Home
    at MyApp (J:\JSKingdom\novel\novel-site\.next\server\pages\_app.js:117:3)
    at AppContainer (J:\JSKingdom\novel\novel-site\node_modules\next\dist\next-server\server\render.js:25:899)
"antd": "^4.13.0",
"next": "10.0.7",
"react": "17.0.1",
"react-dom": "17.0.1",
// index.js
import {
  Form,
  Select,
  InputNumber,
  DatePicker,
  Switch,
  Slider,
  Button,
} from 'antd';
import Link from 'next/link';

const FormItem = Form.Item;
const Option = Select.Option;

export default function Home() {
  return (
    <div style={{ marginTop: 100 }}>
      <Link href="/">
        <a> Go to index </a>
      </Link>
      <Form layout="horizontal">
        <FormItem
          label="Input Number"
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 8 }}
        >
          <InputNumber
            size="large"
            min={1}
            max={10}
            style={{ width: 100 }}
            defaultValue={3}
            name="inputNumber"
          />
          <a href="#">Link</a>
        </FormItem>

        <FormItem
          label="Switch"
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 8 }}
        >
          <Switch defaultChecked name="switch" />
        </FormItem>

        <FormItem
          label="Slider"
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 8 }}
        >
          <Slider defaultValue={70} />
        </FormItem>

        <FormItem
          label="Select"
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 8 }}
        >
          <Select
            size="large"
            defaultValue="lucy"
            style={{ width: 192 }}
            name="select"
          >
            <Option value="jack">jack</Option>
            <Option value="lucy">lucy</Option>
            <Option value="disabled" disabled>
              disabled
            </Option>
            <Option value="yiminghe">yiminghe</Option>
          </Select>
        </FormItem>

        <FormItem
          label="DatePicker"
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 8 }}
        >
          <DatePicker name="startDate" />
        </FormItem>
        <FormItem style={{ marginTop: 48 }} wrapperCol={{ span: 8, offset: 8 }}>
          <Button size="large" type="primary" htmlType="submit">
            OK
          </Button>
          <Button size="large" style={{ marginLeft: 8 }}>
            Cancel
          </Button>
        </FormItem>
      </Form>
    </div>
  );
}

Less-loader requirement and variable issues

Hi, first of all thank you very much for this plugin.

I had an issue where, unlike your example, I got an error of Module not found. Cannot resolve less-loader and so installed the same less-loader version as you are using with this plugin. This fixed that issue, but when importing antd LESS files from my vars file I'm now getting issues such as the following (this one is from @import '~antd/lib/style/dark.less';):


// color palettes
@blue-1: mix(color(~`colorPalette('@{blue-base}', 8) `), @component-background, 15%);
           ^
Error evaluating function `color`: variable @blue-base is undefined
      Error in /usr/dash/node_modules/.pnpm/[email protected][email protected][email protected]/node_modules/antd/lib/style/themes/dark.less (line 5, column 13)

I thought this might be due to a setting about importing files without the .less extension, but changing that doesn't seem to fix it. Could it be about relative pathnames maybe? Not sure if I can think of a way to fix this. Thanks!

Also, I'm using [email protected] to avoid the issues with round(), ceil() etc from antd.

Dependencies:

  "dependencies": {
    "@ant-design/colors": "^5.0.1",
    "@ant-design/icons": "^4.3.0",
    "antd": "^4.9.4",
    "css-loader": "^5.0.1",
    "dynamic-antd-theme": "^0.7.1",
    "less": "3.12.2",
    "less-loader": "7.1.0",
    "next": "10.0.3",
    "next-plugin-antd-less": "^0.1.3",
    "react": "^17.0.1",
    "react-dom": "^17.0.1",
    "tslib": "^2.0.3"
  }

next.config.js:

/* eslint-disable */
const withAntdLess = require('next-plugin-antd-less');

module.exports = withAntdLess({
	lessVarsFilePath: './src/styles/vars.less',
	cssLoaderOptions: {
		sourceMap: false,
		esModule: false,
		modules: {
			mode: 'local',
		},

	},

	webpack(config) {
		return config;
	}
});

src/styles/vars.less:

:root {
  @import '~antd/lib/style/index.less';
}

:root.dark {
  @import '~antd/lib/style/dark.less';
}

Edit: I also see that relativeUrls is true by default in less-loader (https://webpack.js.org/loaders/less-loader/#options) so I am very confused as to why this might happen.

Is less-vars-to-js needed after all?

I just upgraded to v1.0.6 of next-plugin-andt-less. I manually removed less-vars-to-js from my package.json and re-built on Heroku. The build failed because the build process didn't know how to handle the @ character in .less files. Such as @primary-color: green;. I was not able to reproduce this with a production build locally. After re-adding less-vars-to-js , the Heroku build succeeds.

My next.config is pretty stripped down as I'm storing my less variables in the Less files themselves:

const withPlugins = require('next-compose-plugins');
const withAntdLess = require('next-plugin-antd-less');

const lessPlugin = withAntdLess({
  cssLoaderOptions: {
    // https://github.com/webpack-contrib/css-loader#object
    sourceMap: true,
  // Other Config Here...
  },
  webpack(config) {
    return config;
  },
});

module.exports = withPlugins([lessPlugin], {
  images: {
    domains: ['...imgDomain...']
  },
  async redirects() {
    return [...myRedirects...];
  },
});

Note, I am importing @import '~antd/lib/style/themes/default.less'; in my global.less file:

@import '~antd/lib/style/themes/default.less';
@import '~antd/dist/antd.less';

@primary-color: #ff0000;
...

url()s fail to load files

// next.config.js
const withAntdLess = require("next-plugin-antd-less");
module.exports = withAntdLess({});
// styles/foo.less
body { background-image: url("../images/img.jpg"); }
// pages/_app.js
import "../styles/foo.less";

Error:

error - ./images/img.jpg 1:0
Module parse failed: Unexpected character '�' (1:0)

Similar for font files.

This does not happen in .css files.

Expectation: use the built in file-loader for url() refs from .less files.

Workaround: add this custom loader with a specified issuer:

  webpack(config, nextConfig) {
    config.module.rules.push({
      test: /\.(jpe?g|png|gif|svg|ttf|woff2?|eot)$/,
      issuer: /\.less$/,
      use: {
        loader: require.resolve("next/dist/compiled/file-loader"),
        options: {
          name: "static/media/[name].[hash].[ext]",
        },
      },
    });
    return config;
  },

请教一个问题

我看到你在这里配置了这个属性,我看了css-loader的文档,还是不太明白这个配置有什么用?我试着不设置这个属性,看起来好像也没什么问题

exportGlobals: true,

希望得到解答,谢谢!

How to avoid modifying global styles?

If i need to integrate ant-design as a part of an existing website, it's likely i want to prevent ant-design to override global styles. How can i do this?

image

Can we prevent global.less from loading?

Share repo of example demo

Hi, please can you add the files of the example working? so it's possible to have a look at it as reference.

Also, I noticed a small detail to edit in the documentation: in Usage, it should be just .babelrc rather than .babelrc.js?

Thanks!

Inline JavaScript is not enabled. Is it set in your options? [How to enable this in config?]

Getting this error when building nexjs app with yarn build command, After configuring as u mentioned in doc.

Error-Log:

error - ./node_modules/antd/lib/button/style/index.less ((webpack)/css-loader/cjs.js??ref--5-oneOf-3-1!(webpack)/postcss-loader/cjs.js??ref--5-oneOf-3-2!(webpack)/resolve-url-loader??ref--5-oneOf-3-3!./node_modules/less-loader/dist/cjs.js??ref--5-oneOf-3-4!./node_modules/antd/lib/button/style/index.less)

// ant-design/ant-motion#44
.bezierEasingMixin();
^
Inline JavaScript is not enabled. Is it set in your options?
in /Volumes/Mac-Util/Projects/thrive/vidar/node_modules/antd/lib/style/color/bezierEasing.less (line 110, column 0)

nextjs.config.js:
const withAntdLess = require('next-plugin-antd-less'); module.exports = withAntdLess({ javascriptEnabled: true, modifyVars: { '@primary-color': 'red' }, lessVarsFilePath: './styles/antd_theme.less', cssLoaderOptions: {}, webpack(config) { return config; }, });

[Question] Does your plugin work with @ant-design?

Hello,

Really great plugin to begin with antd and less. Quick question, do you know a way how to add support for @ant-design (layouts, tables, fields, utils & etc)?
Having quite a lot of issues (errors & warning) with that right now (SyntaxError: Unexpected token 'export', ./index.less error and more).

Thanks for the tips, if you have any!

Exception in webpack while loading next-plugin-antd-less externals

While trying to following the instructions to debug the nextjs app using --inspect and chrome://inspect the debugger breaks at this exception. I tracked it to external handling in the webpack config for next-plugin-antd-less. Would you have any tips on how to move forward or workaround this?

{
"code": "MODULE_NOT_FOUND",
"requireStack": [
"/../node_modules/next/dist/build/webpack-config.js",
"/../node_modules/next/dist/server/hot-reloader.js",
"/../node_modules/next/dist/server/next-dev-server.js",
"/../node_modules/next/dist/server/next.js",
"/../node_modules/next/dist/server/lib/start-server.js",
"/../node_modules/next/dist/cli/next-dev.js",
"/../node_modules/next/dist/bin/next"
]
}

Cannot find module 'next-plugin-loader?middleware=on-init-server!'

Error: Cannot find module 'next-plugin-loader?middleware=on-init-server!'
"Error: Cannot find module 'next-plugin-loader?middleware=on-init-server!'
Require stack:

  • /yeticlient/node_modules/next/dist/build/webpack-config.js
  • /yeticlient/node_modules/next/dist/server/hot-reloader.js
  • /yeticlient/node_modules/next/dist/server/next-dev-server.js
  • /yeticlient/node_modules/next/dist/server/next.js
  • /yeticlient/node_modules/next/dist/server/lib/start-server.js
  • /yeticlient/node_modules/next/dist/cli/next-dev.js
  • /yeticlient/node_modules/next/dist/bin/next
    at Function.Module.resolveFilename (internal/modules/cjs/loader.js:966:15)
    at Function.mod.resolveFilename (/yeticlient/node_modules/next/dist/build/webpack/require-hook.js:4:1784)
    at Function.resolve (internal/modules/cjs/helpers.js:78:19)
    at /yeticlient/node_modules/next/dist/build/webpack-config.js:82:257
    at new Promise ()
    at /yeticlient/node_modules/next/dist/build/webpack-config.js:82:220
    at handleExternals (/yeticlient/node_modules/next/dist/build/webpack-config.js:51:23)
    at Array.webpackConfig.externals (/yeticlient/node_modules/next/dist/build/webpack-config.js:82:149)
    **
    at webpackConfig.externals (/yeticlient/node_modules/next-plugin-antd-less/overrideWebpackConfig.js:311:62)
    **
    at handleExternals (/yeticlient/node_modules/next/dist/compiled/webpack/bundle4.js:57292:17)
    at next (/yeticlient/node_modules/next/dist/compiled/webpack/bundle4.js:57280:9)
    at handleExternals (/yeticlient/node_modules/next/dist/compiled/webpack/bundle4.js:57285:7)
    at /yeticlient/node_modules/next/dist/compiled/webpack/bundle4.js:57315:5
    at /yeticlient/node_modules/next/dist/compiled/webpack/bundle4.js:64070:5
    at AsyncSeriesWaterfallHook.eval [as callAsync] (eval at create (/yeticlient/node_modules/next/dist/compiled/webpack/bundle4.js:43435:10), :4:1)
    at AsyncSeriesWaterfallHook.lazyCompileHook (/yeticlient/node_modules/next/dist/compiled/webpack/bundle4.js:43372:20)"

In package.json, use this script:
"debug": "NODE_OPTIONS='--inspect=0.0.0.0:9229' next dev",

Attach to the application with chrome://inspect

This is line 311 on the code;

[                                                                                                           
          // webpack4                                                                                               
          (ctx, req, cb) => {                                                                                       
            if (req.match(ANTD_STYLE_REGX)) return cb();                                                            
                                                                                                                    
            if (typeof exts[0] === 'function') return exts[0](ctx, req, cb);        -- LINE 311                                
            else return cb();                                               
          },                                                                
          ...(typeof exts[0] === 'function' ? [] : exts),                    
        ];                                        

Inline JavaScript is not enabled

I'm getting the following error when using your package.


// https://github.com/ant-design/ant-motion/issues/44
.bezierEasingMixin();
^
Inline JavaScript is not enabled. Is it set in your options?
      in node_modules/antd/lib/style/color/bezierEasing.less (line 110, column 0)

I have found out that javascriptEnabled is being set to true in the following snippet but the option is erroneously nested within the lessOptions object.

const lessLoaderIndex = lessModule.use.findIndex((item) => `${item.loader}`.includes('sass-loader'));
lessModule.use.splice(lessLoaderIndex, 1, {
  loader: 'less-loader',
  options: {
    lessOptions: {
      javascriptEnabled: true,
      modifyVars,
    },
  },
});

Instead the options should be set to true like this:

const lessLoaderIndex = lessModule.use.findIndex((item) => `${item.loader}`.includes('sass-loader'));
lessModule.use.splice(lessLoaderIndex, 1, {
  loader: 'less-loader',
  options: {
    javascriptEnabled: true,
    modifyVars,
  },
});

Importing css or scss file no longer possible

Error CSS Modules cannot be imported from within node_modules. when trying to import css or scss file directly in jsx components.

import styles from './DefaultLayout.module.scss'

The code causing this:

rules[1].oneOf.splice(sassModuleIndex, 1, lessModule);

I think we are supposed to insert the lessModule instead of replacing sassModule with it, in order to existing sass loader and it's features.

Proposed fixed:

rules[1].oneOf.splice(sassModuleIndex, 0, lessModule);

Less modules not working

When using the snippet provided in the docs, I cannot make less modules work.

Here is my setup:
"next-plugin-antd-less": "^0.0.6"
"next": "9.5.3"

/// next.config.js
const withAntdLess = require('next-plugin-antd-less');
const config = withAntdLess({
	lessVarsFilePath: './src/styles/theme.less',
	cssLoaderOptionsModules: {
		localIdentName: '[local]___[hash:base64:5]',
	},
});

module.exports = config;
/// .babelrc
{
	"presets": [
		"next/babel"
	],
	"plugins": [
		[
			"import",
			{
				"libraryName": "antd",
				"style": true
			}
		]
	]
}

Edit: I just read the docs again. Is this plugin even supposed to enable less modules? If not, please feel free to close this issue.

NextJS/antd/Less: Module parse failed: Unexpected character '@' (1:0)

Hey good people, I installed the version "^0.3.0"

But I am getting this error when trying to build:

image

next.config.js

const withAntdLess = require("next-plugin-antd-less");

const withPWA = require("next-pwa");
const runtimeCaching = require("next-pwa/cache");
const withPlugins = require("next-compose-plugins");
const optimizedImages = require("next-optimized-images");

const isProduction = process.env.NODE_ENV === "production";

module.exports = withPWA({
  pwa: {
    disable: !isProduction,
    dest: "public",
    register: true,
    runtimeCaching,
  },
});

module.exports = withAntdLess({
  lessVarsFilePath: "./theme/less/theme.less",
  webpack(config) {
    config.module.rules.push({
      test: /\.(png|jpg|jpeg|gif|svg|eot|ttf|woff|woff2)$/,
      use: {
        loader: "url-loader",
      },
    });

    return config;
  },
});

module.exports = withPlugins([optimizedImages]);

.babelrc

{
  "env": {
    "development": {
      "presets": ["next/babel"]
    },
    "production": {
      "presets": ["next/babel"]
    },
    "test": {
      "presets": [
        [
          "next/babel",
          {
            "preset-env": {
              "modules": "commonjs"
            }
          }
        ]
      ],
      "plugins": ["istanbul"]
    }
  },
  "plugins": [
    "react-optimized-image/plugin",
    [
      "import",
      {
        "libraryName": "antd",
        "style": true
      }
    ]
  ]
}

require.extensions is not defined

Hi, @SolidZORO
require.extensions is deprecated and no longer maintained...and it throws errors .... Cannot set property '.less' on undefined.
These errors are thrown only if you use a pre-bundled next config with webpack....

And I have a simple solution.
Can we add a check like that below...........So if the user has require.extensions it will use that and everything will work as usual......but if he doesn't have it because have another node version or have a bundled config it will not throw errors but also will work ok.

// fix: prevents error when .less files are required by node
if (require && require.extensions) {
  require.extensions['.less'] = () => {};
}

Global styles not included in production build

When I create a production build of my Next.js project, global ant design styles are not being applied on pages with no ant design components, even when I import antd/dist/antd.less directly within my _app.js file.

Reproducible setup:

/// package.json
{
  "name": "my-app",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start"
  },
  "dependencies": {
    "antd": "^4.6.5",
    "babel-plugin-import": "^1.13.0",
    "next": "9.5.3",
    "next-plugin-antd-less": "^0.0.6",
    "react": "16.13.1",
    "react-dom": "16.13.1"
  }
}
/// .babelrc
{
  "presets": [
    "next/babel"
  ],
  "plugins": [
    [
      "import",
      {
        "libraryName": "antd",
        "style": true
      }
    ]
  ]
}
/// next.config.js
const withAntdLess = require('next-plugin-antd-less');

module.exports = withAntdLess();
/// pages/_app.js
import 'antd/dist/antd.less'; // This basically does nothing

export default function MyApp({ Component, pageProps }) {
  return <Component {...pageProps} />
};
/// pages/index.js
export default function Home() {
  return (
    <div>
      <h1>Hallo Welt!</h1>
    </div>
  );
}

How to get rid of file matching *.module.less?

I try this plugin and it works like a charm to me. Howerver, I'm facing one issue that I want to use style.less instead of style.module.less. I try some configuration with cssLoaderOptions as below, but seems nothing work for me. Any advice or solution on this?

// next.config.js
const withAntdLess = require("next-plugin-antd-less");

module.exports = withAntdLess({
  // optional
  lessVarsFilePath: "./src/styles/theme/variables.less",

  // optional https://github.com/webpack-contrib/css-loader#object
  cssLoaderOptions: {
    modules: {
      auto: (resourcePath) => resourcePath.endsWith(".less"),
    },
  },

  webpack(config) {
    return config;
  },
});

Variables don't work

Hi,

I have the following build:

"antd": "^4.15.4"
"next": "10.1.3"
"next-plugin-antd-less": "^1.1.4"
"babel-plugin-import": "^1.13.3",
"babel-plugin-superjson-next": "^0.2.3",
"less": "^2.7.3",
 "@zeit/next-less": "^1.0.1",

my next.config.js file content:

const path = require('path');
const withAntdLess = require('next-plugin-antd-less');

module.exports = withAntdLess({
    env: {
        STRAPI_API_URL: 'http://localhost:1337',
    },
    sassOptions: {
        includePaths: [path.join(__dirname, 'styles')],
    },
    // optional
    lessVarsFilePath: './styles/antd.variables.less',
    // optional
    lessVarsFilePathAppendToEndOfContent: false,
    // optional https://github.com/webpack-contrib/css-loader#object
    cssLoaderOptions: {},


    // Other Config Here...

    webpack: (config, {buildId, dev, isServer, defaultLoaders, webpack}) => {
        if (!isServer) {
            config.node = {
                fs: 'empty'
            }
        }
        return config
    },
});

.babelrc.js file is in place:

module.exports = {
    presets: [['next/babel']],
    plugins: [
        ['superjson-next'],
        ['import', { libraryName: 'antd', style: true }]
    ],
};

I have /styles/antd.less file, which I import as a global in my next js app. The content of this file:

@import "~antd/dist/antd.less";
@import "antd.app.less";

/styles/antd.app.less file has my custom global styles

And /styles/antd.variables.less file has all variables I want to override (everything is set to red color for testing purposes):

@import '~antd/lib/style/themes/default.less';

@primary-color: #f00; // primary color for all components
@link-color: #f00; // link color
@success-color: #f00; // success state color
@warning-color: #f00; // warning state color
@error-color: #f5222d; // error state color
@font-size-base: 14px; // major text font size
@heading-color: rgba(255, 8, 8, 0.85); // heading text color
@text-color: rgba(255, 0, 0, 0.65); // major text color
@text-color-secondary: rgba(255, 1, 1, 0.45); // secondary text color
@disabled-color: rgba(255, 0, 0, 0.25); // disable state color
@border-radius-base: 4px; // major border radius
@border-color-base: #ff0000; // major border color
@box-shadow-base: 0 2px 8px rgba(253, 0, 0, 0.15); // major shadow for layers

I've tried with @import '~antd/lib/style/themes/default.less'; and without it.

Same result all the time, variables are still have default values.
Moreover, I have some weird behaviour of antd submenu component.
It's rendering all the elements correctly, when I hover the submenu it adds appropriate classes, but I cannot see submenu on the screen. Seems like styles are messed up, I don't think it's compiled correctly.

not loading other .less files in next build

Hi I jumped into the issue that it works fine on the dev mode but when I do next build and try next start. I found that the less styles from antd works fine but all other .less files imported in JSX are not working.

Here's my next.config.js file.

const withAntdLess = require('next-plugin-antd-less')

module.exports = withAntdLess({
  // optional
  modifyVars: {
    '@primary-color': '#04f',
    '@font-family': 'Montserrat',
  },
  // optional
  lessVarsFilePath: './src/styles/variable.less',
  // optional https://github.com/webpack-contrib/css-loader#object
  cssLoaderOptions: {},
  i18n: {
    locales: [
      'en',
      'es',
      'zh-Hans',
      'zh-Hant',
      'ja',
      'ko',
      'vi',
      'th',
    ],
    defaultLocale: 'en',
  },
  webpack(config) {
    return config
  },
  serverRuntimeConfig: {
    // Will only be available on the server side
  },
  publicRuntimeConfig: {
    // Will be available on both server and client
    API_URL: process.env.API_URL,
    APP_URL: process.env.APP_URL,
  },
})

What is lessVarsFilePath for?

Can you provide a quick explanation of the lessVarsFilePath setting?

I get that modifyVars is for swapping in different values for Ant Design default less variables, but I'm a little confused by the additional lessVarsFilePath setting.

What variables should we be putting in variables.less?

How is this different than importing global styles into _app using require('./styles.less');?

dynamic variables

i have to change my palette base on request , with latest less in window we have less.modifyVars({
'@bgcolor': 'blue',
'@textcolor': 'red'
});

but i dont have it when i use this package

Compatibility with Ant Pro Components

Hi there! Thanks for the awesome repo.

I've been trying to make use of this repo to enjoy its auto reload feature when a variable change. However, I find that its compatibility with Ant Design Pro is not as straightforward.

How to re-create

I've made a sample repo based on mkn over here: https://github.com/darrist/mkn-with-pro-components

Current Behavior

  1. pro-* css classes is not being loaded to the app. These classes are provided by .less files within the library, and it should be automatically consumed when importing the component.

image
image

Intended Behavior

image

My Assumptions

I am thinking it is possibly related to lacking of less-loader, so that .less files inside the library cannot be loaded correctly.

TypeError: this.getOptions is not a function

Getting this error on version 0.2.2. Works perfectly fine on 0.2.0. Seems that the upgraded less-loader is causing the issue?

error - ./node_modules/antd/lib/style/index.less ((webpack)/css-loader/cjs.js??ref--5-oneOf-3-1!(webpack)/postcss-loader/cjs.js??ref--5-oneOf-3-2!(webpack)/resolve-url-loader??ref--5-oneOf-3-3!./node_modules/less-loader/dist/cjs.js??ref--5-oneOf-3-4!./node_modules/antd/lib/style/index.less)
TypeError: this.getOptions is not a function

Enable CSS Support for Component-Level Styles

My component is generated dynamically based on the user selection, therefore,
I would like to enable CSS Support for Component-Level Styles instead of CSS Module Support.

Is it possible to do this in next-plugin-antd-less?
Thanks.

How to prevent overriding the rules defined in global.scss

Hi SolidZORO,

Thank you for your great plugin. I have changed the default variables but my styles defined in global.scss are overrided by the re-compiled antd styles. Before it was overriding the default antd styles.

It means new-antd.less > global.scss > antd.less.

Is there any way to avoid this?

webpack 5 problem

when i use future: {
webpack5: true,
}
yarn build or dev give me error like screenshot
image

How to make it work with @ant-design/pro-layout

I am trying to add @ant-design/pro-layout to my nextjs project. its working on development with lazy import pro-layout component. but pro layout style is missing on production.

/home/darwis/dev/next-exmpl/with-type-script-app/node_modules/antd/es/layout/style/index.js:1
import '../../style/index.less';
       ^^^^^^^^^^^^^^^^^^^^^^^^

SyntaxError: Unexpected string

[Bug] "TypeError: this.getOptions is not a function" with Next 10.0.9

First of all, Thnak you for your awesome effort
I'm using this pakcage with next 10.0.9. But, when I started my app below message is showed

./node_modules/antd/lib/style/index.less ((webpack)/css-loader/cjs.js??ref--5-oneOf-3-1!(webpack)/postcss-loader/cjs.js??ref--5-oneOf-3-2!(webpack)/resolve-url-loader??ref--5-oneOf-3-3!./node_modules/less-loader/dist/cjs.js??ref--5-oneOf-3-4!./node_modules/antd/lib/style/index.less)
TypeError: this.getOptions is not a function

My package

    "@ant-design/icons": "^4.5.0",
    "@emotion/react": "^11.1.5",
    "@emotion/styled": "^11.1.5",
    "@tanem/react-nprogress": "^3.0.58",
    "antd": "^4.14.0",
    "axios": "^0.21.1",
    "babel-plugin-import": "^1.13.3",
    "bootstrap": "^4.6.0",
    "immer": "^8.0.1",
    "less": "^4.1.1",
    "next": "^10.0.9",
    "next-i18next": "^8.1.1",
    "next-redux-wrapper": "^6.0.2",
    "next-seo": "^4.20.0",
    "react": "^17.0.1",
    "react-bootstrap": "^1.5.2",
    "react-dom": "^17.0.1",
    "react-fast-compare": "^3.2.0",
    "react-icons": "^4.2.0",
    "react-redux": "^7.2.2",
    "redux": "^4.0.5",
    "redux-saga": "^1.1.3",
    "sass": "^1.32.8"
"next-plugin-antd-less": "^0.3.0",

Production build missing css

Hey, I'm trying to replace @zeit/next-less with this plugin. Everything works fine in development but production build is missing css for some components. For example Button has css but Table css does not get included in the css bundle.

next.config.js:

require("@app/config");
const compose = require("lodash/flowRight");
const { locales, defaultLocale } = require("./i18n.js");
const AntDDayjsWebpackPlugin = require("antd-dayjs-webpack-plugin");

if (!process.env.ROOT_URL) {
  if (process.argv[1].endsWith("/depcheck")) {
    /* NOOP */
  } else {
    throw new Error("ROOT_URL is a required envvar");
  }
}

// eslint-disable-next-line @typescript-eslint/no-unused-vars
(function (process = null) {
  // You *must not* use `process.env` in here, because we need to check we have
  // those variables. To enforce this, we've deliberately shadowed process.
  module.exports = () => {
    const fs = require("fs");
    const path = require("path");

    const withAntdLess = require("next-plugin-antd-less");
    const lessToJS = require("less-vars-to-js");

    // Where your antd-custom.less file lives
    const themeVariables = lessToJS(
      fs.readFileSync(
        path.resolve(__dirname, "../assets/antd-custom.less"),
        "utf8"
      )
    );
    const withNextTranslate = require("next-translate");

    return compose(
      withAntdLess,
      withNextTranslate
    )({
      poweredByHeader: false,
      distDir: `../.next`,
      trailingSlash: false,
      lessVarsFilePath: path.resolve(__dirname, "../assets/antd-custom.less"),
      modifyVars: themeVariables,
      i18n: {
        locales,
        defaultLocale,
      },
      webpack(config, { webpack, dev, isServer }) {
        const makeSafe = (externals) => {
          if (Array.isArray(externals)) {
            return externals.map((ext) => {
              if (typeof ext === "function") {
                return (context, request, callback) => {
                  if (/^@app\//.test(request)) {
                    callback();
                  } else {
                    return ext(context, request, callback);
                  }
                };
              } else {
                return ext;
              }
            });
          }
        };

        const externals =
          isServer && dev ? makeSafe(config.externals) : config.externals;

        return {
          ...config,
          plugins: [
            ...config.plugins,
            new webpack.DefinePlugin({
              /*
               * IMPORTANT: we don't want to hard-code these values, otherwise
               * we cannot promote a bundle to another environment. Further,
               * they need to be valid both within the browser _AND_ on the
               * server side when performing SSR.
               */
              "process.env.ROOT_URL":
                "(typeof window !== 'undefined' ? window.__GRAPHILE_APP__.ROOT_URL : process.env.ROOT_URL)",
              "process.env.T_AND_C_URL":
                "(typeof window !== 'undefined' ? window.__GRAPHILE_APP__.T_AND_C_URL : process.env.T_AND_C_URL)",
              "process.env.SENTRY_DSN":
                "(typeof window !== 'undefined' ? window.__GRAPHILE_APP__.SENTRY_DSN : process.env.SENTRY_DSN)",
            }),
            new webpack.IgnorePlugin(
              // These modules are server-side only; we don't want webpack
              // attempting to bundle them into the client.
              /^(node-gyp-build|bufferutil|utf-8-validate)$/
            ),
            new AntDDayjsWebpackPlugin(),
          ],
          externals: [
            ...(externals || []),
            isServer ? { "pg-native": "pg/lib/client" } : null,
          ].filter((_) => _),
        };
      },
    });
  };
})();

.babelrc:

{
  "presets": ["next/babel"],
  "plugins": [
    [
      "import",
      {
        "libraryName": "antd",
        "style": true
      }
    ],
    [
      "import",
      {
        "libraryName": "lodash",
        "libraryDirectory": "",
        "camel2DashComponentName": false
      },
      "lodash"
    ]
  ],
  "env": {
    "development": {
      "presets": [
        [
          "next/babel",
          {
            "preset-env": {
              "targets": {
                "node": "current",
                "browsers": "last 2 chrome versions"
              }
            }
          }
        ]
      ]
    }
  }
}

_app.tsx:

...
import "antd/dist/antd.less";
import "../styles.less";
...

styles.less

@import "~antd/lib/style/themes/default.less";

package.json

{
  "dependencies": {
    "antd": "4.11.2",
    "antd-dayjs-webpack-plugin": "^1.0.6",
    "dayjs": "1.10.4",
    "less": "^4.1.1",
    "less-vars-to-js": "^1.3.0",
    "next": "^10.0.6",
    "next-plugin-antd-less": "^0.1.4",
    "react": "^17.0.1",
    "react-dom": "^17.0.1",
    "webpack": "^5.19.0"
  },
  "devDependencies": {
    "babel-plugin-import": "^1.13.3",
    "cross-env": "^7.0.3",
    "jest": "^26.6.3"
  }
}

Any ideas what might be wrong with this setup?

Lost - seem to have an issue from an Antd import

error - ./node_modules/antd/lib/divider/style/index.less (./node_modules/css-loader/dist/cjs.js??ref--5-oneOf-3-1!./node_modules/next/dist/compiled/postcss-loader/cjs.js??ref--5-oneOf-3-2!./node_modules/resolve-url-loader??ref--5-oneOf-3-3!./node_modules/less-loader/dist/cjs.js??ref--5-oneOf-3-4!./node_modules/antd/lib/divider/style/index.less)

.@{divider-prefix-cls} {
  .reset-component;
                ^
Unrecognized input. Possibly missing '(' in mixin call.
      Error in /Users/santiago/mp/web/node_modules/antd/lib/divider/style/index.less (line 7, column 18)
Error: Cannot find module '/Users/santiago/mp/web/.next/build-manifest.json'

Any idea what the cause might be?

next.js 10.2.3 breaking woff loader

Had to revert to my previous PR due to an issue only present when building with target: 'serverless' and importing a .woff font. Seems to be a loader issue

Feature: Can I add sideEffects = true ?

  // clone
  const lessModule = clone(sassModule);
  lessModule.test = /\.less$/;
  delete lessModule.issuer;
  lessModule.sideEffects = true;

sideEffect can make use import not require the global less.

tinyColor.less from antd overriding my own styles

I am using your package (1.1.4) and it is loading tinyColor.less after my own css files causing certain antd components to not be rendered with my styles (.ant-btn {}, etc) . Any ideas why this may be happening?

Feature Request: Multiple output files?

Thanks for creating this plugin! It's been a massive help in figuring out how to assemble all these moving pieces together.

Would it be possible to leverage your plugin to allow for multiple outputted files at build time? I have a use case where I have multiple white label tenants each requiring their own primary colors on top of the application defaults. I think the naive approach would to be to style each white label tenant's styles individually, overwriting defaults. But I'd have to update that every time Ant releases a new component.

What I'd love to do is to be able to specify multiple files, each using a custom lessVarsFilePath. I would then import the appropriate pre-built CSS file in my app. At least that way I could depend on a custom @primary-color per white label tenant.

Something like this as a next.config.js:

const withPlugins = require('next-compose-plugins');
const withAntdLess = require('next-plugin-antd-less');

const tenant1 = withAntdLess({
  lessVarsFilePath: './src/styles/antd-custom-tenant1.less',
  cssLoaderOptions: {
  webpack(config) {
    return config;
  },
});
const tenant2 = withAntdLess({
  lessVarsFilePath: './src/styles/antd-custom-tenant2.less',
  cssLoaderOptions: {
  webpack(config) {
    return config;
  },
});

module.exports = withPlugins([tenant1, tenant2], {
    // ...next config
  },
});

I know the above does not work, it just defaults to whatever variables were defined in my tenant2 config.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.