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

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.

About this issue

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

Most upvoted comments

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"
  }

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 }]
    ]
}

I think I have 😁 …

I had to move the plugin code from the isServer block.

const withCss = require('@zeit/next-css')
const FilterWarningsPlugin = require('webpack-filter-warnings-plugin')

module.exports = withCss({
  webpack: (config, { isServer }) => {
    config.plugins.push(
      new FilterWarningsPlugin({
        // ignore ANTD chunk styles [mini-css-extract-plugin] warning
        exclude: /Conflicting order/,
      })
    );

    if (isServer) {
      const antStyles = /antd\/.*?\/style\/css.*?/
      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',
      })
    }

    // Fixes npm packages that depend on `fs` module
    config.node = {
      fs: 'empty'
    }

    return config
  },
  distDir: "../../dist/client"
})

Just like that warnings are gone!

Thank you. I saw the code but I need to know exactly what causes this problem?

I have a similar problem with @ant-design/layout package. I’ve slowed the problem by using dynamic imports. Example: https://github.com/8iq/nodejs-hackathon-boilerplate-starter-kit/tree/f3779ff2ffd7b70ed98ad0e998923971372b7907/apps/_example04antpro

Or master branch: https://github.com/8iq/nodejs-hackathon-boilerplate-starter-kit/tree/master/apps/_example04antpro

because server don’t know *.less, just browser know it. so we need to deal with this.

I replace all scss files to *.module.less. But I still get warning

As far as I know, less has not been added to the next9 box yet, and therefore it will not be possible to work with less without configuring the next.config

@maotora In fact, I am very dissatisfied with the plugin ecosystem of next.js, it is like a black box, and there are many bugs. If it is as easy to use as Gatsby’s plugin, there will be no problems. So I wrote this part of webpack independently and treat it like normal webpack. (Of course, this is also troublesome for people without webpack configuration experience. Also, you need to pay attention to the css-loader version and pay attention to package.json)

source: https://github.com/SolidZORO/leaa/blob/legacy-www/packages/leaa-www/tools/next/next-webpack.js

@maotora I haven’t written next.js code for a while, you may need to debug it yourself. 😭

you can see here. https://github.com/SolidZORO/leaa/blob/legacy-www/packages/leaa-www/tools/next/next-webpack.js