question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Next.js 9 with antd + less, yarn build get an error

See original GitHub issue

QUESTION

yarn dev is work, but yarn build get an error.

> Build error occurred
{ /<PROJECT-PATH>/node_modules/antd/lib/style/index.less:1
(function (exports, require, module, __filename, __dirname) { @import './themes/index';
                                                              ^

SyntaxError: Invalid or unexpected token
    at new Script (vm.js:79:7)
    at createScript (vm.js:251:10)
    at Object.runInThisContext (vm.js:303:10)
    at Module._compile (internal/modules/cjs/loader.js:656:28)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:699:10)
    at Module.load (internal/modules/cjs/loader.js:598:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:537:12)
    at Function.Module._load (internal/modules/cjs/loader.js:529:3)
    at Module.require (internal/modules/cjs/loader.js:636:17)
    at require (internal/modules/cjs/helpers.js:20:18) type: 'SyntaxError', '$error': '$error' }
error Command failed with exit code 1.

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Reactions:18
  • Comments:30 (4 by maintainers)

github_iconTop GitHub Comments

24reactions
SolidZOROcommented, Jul 22, 2019

RESOLVE

i found that with-ant-design-less can handles this error, but project/pages’s less style don’t work. so I wrote a next-antd.config.js to solve this problem.

next.config.js

const fs = require('fs');
const path = require('path');

const lessToJS = require('less-vars-to-js');
const FilterWarningsPlugin = require('webpack-filter-warnings-plugin');

const withImage = require('./configs/next-image.config');
const withDotenv = require('./configs/next-dotenv.config');
const withAntd = require('./configs/next-antd.config');

const antdVariables = lessToJS(fs.readFileSync(path.resolve(__dirname, './styles/variables.less'), 'utf8'));

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

module.exports = withDotenv(
  withImage(
    withAntd({
      cssModules: true,
      cssLoaderOptions: {
        sourceMap: false,
        importLoaders: 1,
      },
      lessLoaderOptions: {
        javascriptEnabled: true,
        modifyVars: antdVariables,
      },
      webpack: config => {
        config.plugins.push(
          new FilterWarningsPlugin({
            // ignore ANTD chunk styles [mini-css-extract-plugin] warning
            exclude: /mini-css-extract-plugin[^]*Conflicting order between:/,
          }),
        );

        return config;
      },
    }),
  ),
);

next-antd.config.js

const cssLoaderConfig = require('@zeit/next-css/css-loader-config');

module.exports = (nextConfig = {}) => ({
  ...nextConfig,
  ...{
    webpack(config, options) {
      if (!options.defaultLoaders) {
        throw new Error(
          'This plugin is not compatible with Next.js versions below 5.0.0 https://err.sh/next-plugins/upgrade',
        );
      }

      const { dev, isServer } = options;
      const { cssModules, cssLoaderOptions, postcssLoaderOptions, lessLoaderOptions = {} } = nextConfig;

      // for all less in clint
      const baseLessConfig = {
        extensions: ['less'],
        cssModules,
        cssLoaderOptions,
        postcssLoaderOptions,
        dev,
        isServer,
        loaders: [
          {
            loader: 'less-loader',
            options: lessLoaderOptions,
          },
        ],
      };

      config.module.rules.push({
        test: /\.less$/,
        exclude: /node_modules/,
        use: cssLoaderConfig(config, baseLessConfig),
      });

      // for antd less in client
      const antdLessConfig = {
        ...baseLessConfig,
        ...{ cssModules: false, cssLoaderOptions: {}, postcssLoaderOptions: {} },
      };

      config.module.rules.push({
        test: /\.less$/,
        include: /node_modules/,
        use: cssLoaderConfig(config, antdLessConfig),
      });

      // for antd less in server (yarn build)
      if (isServer) {
        const antdStyles = /antd\/.*?\/style.*?/;
        const rawExternals = [...config.externals];

        config.externals = [
          (context, request, callback) => {
            if (request.match(antdStyles)) {
              return callback();
            }

            if (typeof rawExternals[0] === 'function') {
              rawExternals[0](context, request, callback);
            } else {
              callback();
            }
          },
          ...(typeof rawExternals[0] === 'function' ? [] : rawExternals),
        ];

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

      if (typeof nextConfig.webpack === 'function') {
        return nextConfig.webpack(config, options);
      }

      return config;
    },
  },
});

.babelrc.js

module.exports = {
  presets: [['next/babel']],
  plugins: [
    [
      'import',
      {
        libraryName: 'antd',
        libraryDirectory: 'lib',
        style: true,
      },
    ],
  ],
  ignore: ['node_modules'],
};

package.json

 "devDependencies": {
    "@zeit/next-css": "^1.0.2-canary.2",
    "@zeit/next-less": "^1.0.1",
    "less": "^3.9.0",
    "less-vars-to-js": "^1.3.0",
    "null-loader": "^3.0.0",
    "webpack-filter-warnings-plugin": "^1.2.1"
  }
5reactions
bahmannejaticommented, Mar 9, 2020

Here are the files that works fine for me :

"next": "9.2.2"
"less": "^3.11.1"
"antd": "^4.0.2"

next.config.js

const withLess = require('@zeit/next-less')

module.exports = () => {
    return withLess({
        lessLoaderOptions: {
            modifyVars: {
                'primary-color': '#066',
            },
            javascriptEnabled: true,
        },
        webpack: (config, { isServer }) => {
            if (isServer) {
              const antStyles = /antd\/.*?\/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
        },
    })
}

.babelrc

{
    "presets": ["next/babel"],
    "plugins": [
        ["import", { "libraryName": "antd", "style": true }]
    ]
}
Read more comments on GitHub >

github_iconTop Results From Across the Web

How to configure nextjs 9 and ant design less compatibility?
It seems there is a compatibility problem with ant design and I found some sources but not get it though! reactjs · next.js...
Read more >
How to use Ant Design with Next.js
Install Ant Design. We can install Ant Design to our Next.js app with a single command: yarn add antd.
Read more >
next-transpile-modules
I have trouble with transpilation and my custom .babelrc. If you get a transpilation error when using a custom Babel configuration, make sure ......
Read more >
Building Forms with Next.js
Learn how to create forms with Next.js, from the form HTML element to advanced concepts ... i.e., GET or POST used to send...
Read more >
Next JS with Ant Design
Getting Started · Add ant design package yarn add antd · Add other ant design dependencies for next js like zeit/css, ziet/less and...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found