Nextjs摸鱼进阶一: 配置Typescript编译环境

5,199 阅读1分钟

    用Next.js开发项目有一段时间了,最近萌生了一个加上Typescript折腾一下自己的想法。虽说上班有鱼摸是好事,有时间还是要提升一下自己呀~ (* ̄︶ ̄)

一、首先来配置一下环境吧

1.1 我就直接用yarn啦,相信npm|yarn都难不到在座的各位
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
1.2 文件目录:
components/
--| header.js
pages/
--| index.js
.babelrc
next.config.js //nextjs配置文件
server.js //本地服务
tsconfig.json //ts配置文件
package.json

二、配置Typescript

Tip: VSCode TS+React提示插件可以使用Reactjs code snippets

2.1 在项目根目录创建.babelrc
{
  "presets": [
    "next/babel",
    "@zeit/next-typescript/babel"
  ]
}
2.2 在项目根目录创建tsconfig.json

paths - 配置@components快捷路径,否则组件中引入tsx组件会报:找不到模块

{
  "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

在项目根目录创建next.config.js,配置nextjs打包环境

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: ''
  }
})

四、配置server.js本地服务

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}`);
        }
      }
    });
  });