鹦哥 發表於 2019-11-29 11:33:00

Next.js中使用antd组件

<p>Next.js中不能直接使用css,需要我们自行解决:</p>
<h2>一、先解决不能引入css,只能使用&lt;style jsx&gt;的问题</h2>
<p>(1)需要安装 @zeit/next-css : npm install&nbsp; --save&nbsp;@zeit/next-css</p>
<p>(2)安装成功,需要在根目录建立next.config.js</p>
<div class="cnblogs_code">
<pre>const withCss = require('@zeit/next-css'<span style="color: rgba(0, 0, 0, 1)">)

</span><span style="color: rgba(0, 0, 255, 1)">if</span>(<span style="color: rgba(0, 0, 255, 1)">typeof</span> require !== 'undefined'<span style="color: rgba(0, 0, 0, 1)">){
    require.extensions[</span>'.css']=file=&gt;<span style="color: rgba(0, 0, 0, 1)">{}
}

module.exports </span>= withCss({})</pre>
</div>
<p>(3)重启项目</p>
<h2>二、引入antd</h2>
<p>(1)先安装Ant Design 库: npm install --save antd</p>
<p>(2)再安装babel-plugin-import: npm install --save babel-plugin-import</p>
<p>&nbsp; &nbsp; &nbsp; &nbsp;还需要根目录新建 .babelrc 文件进行配置</p>
<p>  目的:只加载项目中用到的模块,这就需要我们用到一个<code>babel-plugin-import</code>文件,配置好了 .babelrc 就不会把Ant Design打包到生产环境。</p>
<div class="cnblogs_code">
<pre><span style="color: rgba(0, 0, 0, 1)">{
    </span>"presets":["next/babel"], <span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> Next.js的配置文件,相当于继承了它本身的所有配置</span>
    "plugins":[<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> 增加新的插件,这个插件就是让antd可以按需引入,包括css</span>
<span style="color: rgba(0, 0, 0, 1)">      [
            </span>"import"<span style="color: rgba(0, 0, 0, 1)">,
            {
                </span>"libraryName":"antd"<span style="color: rgba(0, 0, 0, 1)">,
                </span>"style":"css"<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> 引入css</span>
<span style="color: rgba(0, 0, 0, 1)">            }
      ]
    ]
}</span></pre>
</div>
<p>(3)重启项目</p>
<p>(4)在需要的页面引入</p>
<div class="cnblogs_code">
<pre>import '../static/common.css'<span style="color: rgba(0, 0, 0, 1)">
import {Button} from </span>'antd'

<span style="color: rgba(0, 0, 255, 1)">function</span><span style="color: rgba(0, 0, 0, 1)"> Header(){
    </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> (
      </span>&lt;&gt;
            &lt;Button&gt;我是按钮,你是吗&lt;/Button&gt;
      &lt;/&gt;
<span style="color: rgba(0, 0, 0, 1)">      
    )
}
export </span><span style="color: rgba(0, 0, 255, 1)">default</span> Header</pre>
</div>
<p>&nbsp;</p><br><br>
来源:https://www.cnblogs.com/linjiu0505/p/11956717.html
頁: [1]
查看完整版本: Next.js中使用antd组件