nextjs + react + antd 冲突错误解决方案

一、使用了 antd-mobile 而且须要对它进行按需加载,下面是官方的文档,推荐咱们使用 babel-plugin-import。css

 

二、按照 nextjs 官方文档咱们在 .babelrc 中添加插件html

{
  "presets": ["next/babel"],
  "plugins": [
    ["import", { "libraryName": "antd-mobile", "style": true }]
  ]
}

可当我运行的时候报错了,报错以下。最开始感到奇怪,我并无引入这个包,后来发现实际上是 antd-mobile 中有引入它。可是为何会报错呢, 便想到应该是 webpack loader 的问题,我认为是 loader 排除了node_modules。(这里解释一下,node_modules 中的包本应该都是打包好的,可是一些状况下,咱们是直接引入源代码中的模块的,那这样的话咱们就须要让咱们的 loader 解析 node_modules 中的代码,然而有些默认配置就是排除了 node_modules 的,这样就会致使没法解析)。node

 

三、后来我终于想清楚了,首先 next-transpile-modules 的目的就是让 node_modules 中的包可使用 next-babel-loader ,它的文档第一句就是这个意思,我当时理解错误了。webpack

其次咱们再来讲说 webpack.externals 这个配置,好比 nextjs 默认就是以下这样配置的,它把 node_modules 下的 js 做为一个公共的js来处理,当这样配置之后,webpack 就不会去分析 node_modules 下的 js 的依赖了。web

好比我本身在 node_modules 里写一个文件夹 @test,里面是一个 index.js,index.js require了同级的 b.js,而后咱们在 nextjs 的项目代码里引入 @test/index.js ,编译时就会报错,报错的行就在 require('b.js') 这里。babel

再来讲说 next-transpile-modules, 它作了两个事情,第一是从 nextjs 默认的 externals 中,排除掉咱们定义的  transpileModules: ["antd-mobile"],这样 antd-mobile 中的 js 就会被 webpack 正常解析依赖了。然后新建了一个 next-babel-loader ,include 的值是 transpileModules 配置的 ["antd-mobile"]。 因为咱们的 antd-mobile 中的代码不须要被 next-babel-loader 解析,甚至若是使用 next-babel-loader 解析就会报错,所以我前面的配置把它添加的 loader 的 include 给清空了,这样全部的配置就 ok 了。所以咱们只须要它其中的 externals 功能,ok, next.config.js 最终代码以下(  .babelrc  参照上面不变)antd

const withLess = require("@zeit/next-less");
const withCss = require("@zeit/next-css");
const withPlugins = require("next-compose-plugins");
const cssLoaderGetLocalIdent = require("css-loader/lib/getLocalIdent.js");
const path = require('path');

module.exports = withPlugins([withLess,withCss], {
  cssModules: true,
  cssLoaderOptions: {
    camelCase: true,
    localIdentName: "[local]___[hash:base64:5]",
    getLocalIdent: (context, localIdentName, localName, options) => {
      let hz = context.resourcePath.replace(context.rootContext, "");
      if (/node_modules/.test(hz)) {
        return localName;
      } else {
        return cssLoaderGetLocalIdent(
          context,
          localIdentName,
          localName,
          options
        );
      }
    }
  },
  webpack(config){
    if(config.externals){
      const includes = [/antd-mobile/];
      config.externals = config.externals.map(external => {
        if (typeof external !== 'function') return external;
        return (ctx, req, cb) => {
          return includes.find(include =>
            req.startsWith('.')
              ? include.test(path.resolve(ctx, req))
              : include.test(req)
          )
            ? cb()
            : external(ctx, req, cb);
        };
      });
    }
    return config;
  }
});

注意:参考子慕大诗人博——完美融合nextjs和antdless

相关文章
相关标签/搜索