Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Modular antd imports with next.js, next-less, next-typescript, and babel-plugin-import
const withLess = require('@zeit/next-less')
const withTypescript = require('@zeit/next-typescript')
const resolve = require('resolve')
module.exports = withTypescript(withLess({
lessLoaderOptions: {
javascriptEnabled: true,
// theme antd here
modifyVars: {'@primary-color': '#1Dd57A'}
},
webpack: (config, { defaultLoaders, dir, isServer }) => {
defaultLoaders.babel.options.plugins.push(['import', {
'libraryName': 'antd',
'style': true
}])
config.externals = []
if (isServer) {
config.externals.push((context, request, callback) => {
resolve(request, { basedir: dir, preserveSymlinks: true }, (err, res) => {
if (err) {
return callback()
}
// exclude webpack itself and antd from externals
if (res.match(/node_modules[/\\].*\.js/) && !res.match(/node_modules[/\\]webpack/) && !res.match(/node_modules[/\\]antd/)) {
return callback(null, `commonjs ${request}`)
}
callback()
})
})
}
return config
},
}))
@giautm

This comment has been minimized.

Copy link

@giautm giautm commented Jun 13, 2018

@delikat: config.externals = [] this line is the actual fix.

@cristopherDev

This comment has been minimized.

Copy link

@cristopherDev cristopherDev commented Jul 13, 2018

@delikat: this module return -> TypeError: Cannot read property 'push' of undefined, can you help me or list the dependencies need for this work? thanks!!

@dotrung

This comment has been minimized.

Copy link

@dotrung dotrung commented Aug 3, 2018

@cristopherDev this error is caused by plugins of defaultLoaders.babel.options is undefined.
I did a check and find that it exists in next 5.0.0, but not 6.

@Enalmada

This comment has been minimized.

Copy link

@Enalmada Enalmada commented Sep 7, 2018

@delikat this is pretty awesome. Thank you for this!

FYI @cristopherDev Look at my fork for a version that works on next6 with a few fixes
-- fix for styled jsx (typeof require !== 'undefined' from current with-antd-less example)
-- fix for TypeError (defaultLoaders.babel.options.plugins = [])
-- fix for absolute paths (updated config.externals.push code from next.js source and readded antd)
-- I removed typescript because I am not using typescript (I assume that is ok?)

@onury

This comment has been minimized.

Copy link

@onury onury commented Nov 5, 2018

@delikat thanks for this but you said modular imports are working with this but entire css is still loaded in my tests. Am I missing something?

antd-css-size

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment