NO.3 学一点又不会死系列

110 阅读1分钟

背景

学习TypeScript的前期准备,使用webpack初始化一个基本工程。

实现过程

1. 创建基本文件结构

image.png build/webpack.config.js文件内容如下:

const {CleanWebpackPlugin} = require('clean-webpack-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const path = require('path')

const isProd = process.env.NODE_ENV === 'production' // 是否生产环境

function resolve (dir) {
  return path.resolve(__dirname, '..', dir)
}

module.exports = {
  mode: isProd ? 'production' : 'development',
  entry: {
    app: './src/main.ts'
  },

  output: {
    path: resolve('dist'),
    filename: '[name].[contenthash:8].js'
  },

  module: {
    rules: [
      {
        test: /\.tsx?$/,
        use: 'ts-loader',
        include: [resolve('src')]
      }
    ]
  },

  plugins: [
    new CleanWebpackPlugin({
    }),

    new HtmlWebpackPlugin({
      template: './public/index.html'
    })
  ],

  resolve: {
    extensions: ['.ts', '.tsx', '.js']
  },

  devtool: isProd ? 'cheap-module-source-map' : 'cheap-module-eval-source-map',

  devServer: {
    host: 'localhost', // 主机名
    stats: 'errors-only', // 打包日志输出输出错误信息
    port: 8081,
    open: true
  },
}

public/index.html文件内容如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    
</body>
</html>

src/main.js文件内容如下:

import './xxxx'

2. 在终端运行 npm init -y命令,生成package.json文件文件

3. 在终端运行 tsc --init命令,生成tsconfig.json文件

4. 下载依赖

```
"cross-env": "^7.0.3"
"typescript": "^4.7.4"
"webpack": "^4.46.0"
"webpack-cli": "^3.3.12"
"webpack-dev-server": "^3.11.3"
"clean-webpack-plugin": "^4.0.0"
"html-webpack-plugin": "^4.5.2"
"ts-loader": "^8.4.0"
```

5.在package.json文件中配置打包命令

 "scripts": {
    "dev": "cross-env NODE_ENV=development webpack-dev-server --config build/webpack.config.js",
    "build": "cross-env NODE_ENV=production webpack --config build/webpack.config.js"
  }

6.在终端运行 npm run dev命令

结语

学习视频是在B站上找的,跟着视频敲得笔记,感谢作者的分享。