Nextjs摸魚進階一: 配置Typescript編譯環境

    用Next.js開發項目有一段時間了,最近萌生了一個加上Typescript折騰一下本身的想法。雖然說上班有魚摸是好事,有時間仍是要提高一下本身呀~ (* ̄︶ ̄)node

1、首先來配置一下環境吧

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
複製代碼

2、配置Typescript

Tip: VSCode TS+React提示插件能夠使用Reactjs code snippetsreact

2.1 在項目根目錄建立.babelrc
{
  "presets": [
    "next/babel",
    "@zeit/next-typescript/babel"
  ]
}
複製代碼
2.2 在項目根目錄建立tsconfig.json

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"]
}
複製代碼

3、 配置next.config.js

在項目根目錄建立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: ''
  }
})
複製代碼

4、配置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}`);
        }
      }
    });
  });


複製代碼
相關文章
相關標籤/搜索