使用webPack搭建TypeSctipt项目结构

81 阅读2分钟

1.项目依赖包

npm init -y
tsc --init
npm install -D typescript
npm install -D webpack@4.41.5 webpack-cli@3.3.10
npm install -D webpack-dev-server@3.10.2                 
npm install -D html-webpack-plugin@4.0.0-alpha clean-webpack-plugin     
npm install -D ts-loader@4.0.0                               
npm install -D cross-env       

2.各个包的作用

npm init -y
tsc --init 产生对应的ts.config.js文件
npm install -D typescript
npm install -D webpack@4.41.5 webpack-cli@3.3.10
npm install -D webpack-dev-server@3.10.2                     启动开发服务器的
npm install -D html-webpack-plugin@4.0.0-alpha clean-webpack-plugin     对html内容进行打包 / 清除之前打包好的js文件
npm install -D ts-loader@4.0.0                                针对ts文件进行编译处理
npm install -D cross-env                                  涉及跨平台命令

3.在package.json文件进行配置

"scripts": {

    "test": "echo \"Error: no test specified\" && exit 1",

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

  },

4.创建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'), //将打包好的文件放到dist目录里面
  filename: '[name].[contenthash:8].js' //产生的js文件是以app加上8位的哈希值.js来命名的
},

module: {
  rules: [	//rules主要是通过ts-loader这个包针对于ts文件,针对src目录里面的ts和tsx文件进行编译处理操作
    {
      test: /\.tsx?$/,
      use: 'ts-loader',
      include: [resolve('src')]
    }
  ]
},

plugins: [
  new CleanWebpackPlugin({ //会将dist目录中以前打包的js文件进行清楚
  }),

  new HtmlWebpackPlugin({ //针对于./public/index.html进行打包的
    template: './public/index.html'
  })
],

resolve: {
  extensions: ['.ts', '.tsx', '.js'] //针对于'.ts', '.tsx', '.js'这三种文件进行处理引入文件可以不写他的扩展名
},
  //针对于代码的错误提示
devtool: isProd ? 'cheap-module-source-map' : 'cheap-module-eval-source-map',

devServer: {
  host: 'localhost', // 主机名
  stats: 'errors-only', // 打包日志输出输出错误信息
  port: 8081, //端口
  open: true //自定打开浏览器
},
}

5.创建src目录下的main.ts

6.需要创建public文件夹index.html

7.使用npm run dev命令进行项目启动

8.项目结构

image-20220917223040740.png