I’ve been working on projects with next.js for a while now, and I recently came up with the idea of throwing myself into Typescript. Although it is a good thing to have fish at work, have time or to improve themselves ~ (* ~)

First, let’s configure the environment

1.1 I will be with yarn directly, I believe that NPM | yarn everyone here is difficult to be found
npm init -y

yarn add next react react-dom express --save
/ / 1. @ types/react | react - dom to react type definition file
@zeit/ Next-typescript The nextjs configuration supports typescript
yarn add @zeit/next-typescript @types/{react,react-dom} --dev
Copy the code
1.2 File Directory:
Components / - | header. Js pages / -- -- | index. The js. Babelrc next. Config. Js / / nextjs server configuration file. The js / / local service tsconfig. Json //ts configuration file package.jsonCopy the code

Configure Typescript

VSCode TS+React prompts the plugin to use Reactjs code snippets

2.1 Create. Babelrc in the project root directory
{
  "presets": [
    "next/babel"."@zeit/next-typescript/babel"]}Copy the code
2.2 Create tsconfig.json in the project root directory

Paths – Configure the @Components shortcut path, otherwise the component introduced into the TSX component will report: no module found

{
  "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"]}Copy the code

3. Configure next.config.js

Create next. Config. js in the project root directory and configure the NextJS packaging environment

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

4. Configure the server.js local service

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;
// Determine the development environment and production environment
const dev = isDev;
const app = next({ dev });
const handle = app.getRequestHandler();
app.prepare()
  .then((a)= > {
    const server = express();
    server.get(The '*', (req, res) => {
      return handle(req, res);
    });
    server.listen(PORT, err => {
      if (err) throw err;
      const serverUrl = `server running in: http://localhost:${PORT}`;
      // The development environment starts the browser automatically
      if (dev) {
        switch (process.platform) {
          // The MAC system uses the following command to open the URL in the browser
          case 'darwin':
            cp.exec(`open ${serverUrl}`);
            break;
          // Windows uses the following command to open the URL in the browser
          case 'win32':
            cp.exec(`start ${serverUrl}`);
            break;
          // The default MAC system
          default:
            cp.exec(`open ${serverUrl}`); }}}); });Copy the code