用Next.js开发项目有一段时间了,最近萌生了一个加上Typescript折腾一下本身的想法。虽然说上班有鱼摸是好事,有时间仍是要提高一下本身呀~ (* ̄︶ ̄)node
npm init -y
yarn add next react react-dom express --save
// 1. @types/react|react-dom 为React的类型定义文件
// 2. @zeit/next-typescript nextjs 配置支持typescript
yarn add @zeit/next-typescript @types/{react,react-dom} --dev
复制代码
components/
--| header.js
pages/
--| index.js
.babelrc
next.config.js //nextjs配置文件
server.js //本地服务
tsconfig.json //ts配置文件
package.json
复制代码
Tip: VSCode TS+React提示插件能够使用Reactjs code snippetsreact
{
"presets": [
"next/babel",
"@zeit/next-typescript/babel"
]
}
复制代码
paths - 配置@components快捷路径,不然组件中引入tsx组件会报:找不到模块webpack
{
"compilerOptions": {
"allowJs": true,
"allowSyntheticDefaultImports": true,
"jsx": "preserve",
"lib": ["dom", "es2017"],
"module": "esnext",
"moduleResolution": "node",
"noEmit": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"preserveConstEnums": true,
"removeComments": false,
"skipLibCheck": true,
"sourceMap": true,
"strict": true,
"target": "esnext",
"baseUrl":".",
"paths":{
"@components/*":["./components/*"],
"@pages/*":["./pages/*"],
}
},
"exclude": ["node_modules"]
}
复制代码
在项目根目录建立next.config.js
,配置nextjs打包环境web
const path = require('path');
const withTypescript = require('@zeit/next-typescript')
module.exports = withTypescript({
webpack(config, options) {
config.module.rules.push({
test: /\.js$/,
enforce: 'pre',
include: [
path.resolve('components'),
path.resolve('pages'),
],
});
config.devtool = 'cheap-module-inline-source-map';
config.resolve.alias = {
...config.resolve.alias,
'@pages': path.join(__dirname, '.', 'pages'),
'@components': path.join(__dirname, '.', 'components'),
}
return config
},
serverRuntimeConfig: { // Will only be available on the server side
rootDir: path.join(__dirname, './'),
PORT: process.env.NODE_ENV !== 'production' ? 8080 : (process.env.PORT || 8080)
},
publicRuntimeConfig: { // Will be available on both server and client
staticFolder: '/static',
isDev: process.env.NODE_ENV !== 'production' // Pass through env variables
},
env: {
SERVER_HOST: '127.0.0.1:8080'
},
prot: {
SERVER_HOST: ''
}
})
复制代码
const express = require('express');
const cp = require('child_process');
const next = require('next');
const { publicRuntimeConfig, serverRuntimeConfig } = require('./next.config');
const { isDev } = publicRuntimeConfig;
const { PORT } = serverRuntimeConfig;
// 判断开发环境和生产环境
const dev = isDev;
const app = next({ dev });
const handle = app.getRequestHandler();
app.prepare()
.then(() => {
const server = express();
server.get('*', (req, res) => {
return handle(req, res);
});
server.listen(PORT, err => {
if (err) throw err;
const serverUrl = `server running in: http://localhost:${PORT}`;
// 开发环境自动启动游览器
if (dev) {
switch (process.platform) {
//mac系统使用 一下命令打开url在浏览器
case 'darwin':
cp.exec(`open ${serverUrl}`);
break;
//win系统使用 一下命令打开url在浏览器
case 'win32':
cp.exec(`start ${serverUrl}`);
break;
// 默认mac系统
default:
cp.exec(`open ${serverUrl}`);
}
}
});
});
复制代码