Next.js Typescript Integration with Ant Design (antd)
Published on 17 November 2019This article describes how to add the Antd library to Next.js.
This is based off the with-ant-design example in Next.js.
Next configuration
In next.config.js
in the root directory of your Next application, add the
following:
/** See https://github.com/zeit/next.js/tree/canary/examples/with-ant-design */
const withCss = require('@zeit/next-css')
module.exports = withCss({
webpack: (config, { isServer }) => {
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',
})
}
return config
},
});
In babel.config.js
:
module.exports = api => {
return {
presets: ['next/babel'],
plugins: [
[
"import", {
libraryName: 'antd',
style: 'css',
}
]],
};
};
Example usage
We are able to import from both antd
and antd/lib/<component>
.
/*
* An example that imports top-level components from 'antd' and also imports
* from files under 'antd/lib'.
*/
import { TreeSelect } from 'antd';
import { TreeNode, TreeSelectProps } from 'antd/lib/tree-select';
import React from 'react';
const TreeSelectView: React.FC<TreeSelectProps<string[]>> = (props, ref) => {
return (
<TreeSelect
{...props}
treeCheckable
treeData={{}}
treeDefaultExpandAll
style={{ width: 300 }}
showCheckedStrategy="SHOW_PARENT"
ref={ref}
/>
);
};
export default React.forwardRef(TreeSelectView);