前言
最近公司需要使用 Next
結合 React
、 Antd-Mobile
開發服務端渲染的H5,於是就看了些文檔搭建一個簡單地環境記錄下來。
一、搭建基礎環境
1. 使用 yarn
或者 npm
初始化一個文件夾
yarn init
OR
npm init
2. 安裝要使用的包
package.json
整體配置
{
"name": "next-react-demo",
"version": "1.0.0",
"main": "index.js",
"license": "MIT",
"scripts": {
"dev": "next -p 3001",
"build": "next build",
"start": "next start"
},
"dependencies": {
"@babel/plugin-proposal-class-properties": "^7.7.0",
"@babel/plugin-proposal-decorators": "^7.7.0",
"@zeit/next-less": "^1.0.1",
"antd-mobile": "^2.3.1",
"babel-plugin-import": "^1.12.2",
"babel-plugin-module-resolver": "^3.2.0",
"less": "^3.10.3",
"next": "^9.1.3",
"react": "^16.11.0",
"react-dom": "^16.11.0"
}
}
運行 yarn
或 npm install
進行安裝
3. 新建 pages/index.js
文件,寫入以下代碼運行測試
export default () => <div>Welcome to next.js!</div>
運行 npm run dev
命令並打開 http://localhost:3000。 如果你想使用其他端口,可運行 npm run dev – -p <設置端口號>
。
在瀏覽器可看到如下結果:
[外鏈圖片轉存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-6PK1S5M9-1585804373496)(http://60.205.204.237:8080/images/2019/11/12/TIM20191112190005.png)]
二、加入antd-mobile和less
1. 增加 next
配置文件
根目錄下新建 next.config.js
並加入以下配置
const withLess = require('@zeit/next-less')
module.exports = withLess({
cssModules: true,
cssLoaderOptions: {
importaLoaders: 1,
localIdentName: "[local]___[hash:base64:5]",
},
lessLoaderOptions: {
javascriptEnabled: true,
},
webpack(config, options) {
return config
}
})
2. 增加 babel
文件配置
根目錄下新建 .babelrc
文件並加入以下配置
{
"presets": [
"next/babel"
],
"plugins": [
// ES6 語法轉換
["@babel/plugin-proposal-decorators", { "legacy": true }],
["@babel/plugin-proposal-class-properties", { "loose": true }],
// Alias
["module-resolver",{"root": ["./"],"alias": {"styles": "./styles", "@": "./pages"}}],
// 引入Antd-Mobile
["import",{"libraryName": "ant-mobile","libraryDirectory":"lib","style": true}]
]
}
3. 在pages下新建_document.js文件用來自定義Document,並且在頭部加入我們Antd-mobile的css
之前一直搭好之後一直沒有樣式,找了很久才發覺還沒有因爲 Antd-Mobile
的樣式文件,於是就使用了自定義 Document
,在其中引入 Css
。也可以使用其他方案去引用相應的 less
OR sass
文件。
import Document, { Head, Main, NextScript } from 'next/document'
export default class extends Document {
render() {
return (
<html >
<Head>
<meta name="format-detection" content="telephone=no, email=no" />
<meta name="viewport" content="width=device-width,height=device-height, user-scalable=no,initial-scale=1, minimum-scale=1, maximum-scale=1,target-densitydpi=device-dpi" />
<link href="https://cdn.bootcss.com/antd-mobile/2.1.1/antd-mobile.css" rel="stylesheet" />
</Head>
<body >
<Main />
<NextScript />
</body>
</html>
)
}
}
新建 styles/style.less
文件,寫入以下代碼。這裏測試下我們配置的 less
有沒有生效
@h1-color: aqua;
h1{
color: @h1-color;
}
修改 index
文件如下
import React, { Fragment } from 'react';
import { Button , WingBlank , WhiteSpace} from 'antd-mobile';
import Head from 'next/head';
import "../styles/style.less";
const Home = () => (
<Fragment>
<Fragment>
<h1>我是Next的首頁</h1>
<WingBlank>
<Button>默認按鈕</Button><WhiteSpace />
</WingBlank>
</Fragment>
</Fragment>
);
export default Home;
配置完成後可看到以下效果:
總結
這篇文章還是比較小白的,按照所有步驟做的話基本是沒什麼問題的,剩下的就是慢慢去優化項目結構來適配自己的項目。