4. 使用webpack打包TS

下载依赖

  1. yarn add -D typescript
  2. yarn add -D webpack webpack-cli
  3. yarn add -D webpack-dev-server
  4. yarn add -D html-webpack-plugin clean-webpack-plugin
  5. yarn add -D ts-loader
  6. yarn add -D cross-env

入口JS: src/main.ts

  1. // import './01_helloworld'
  2. document.write('Hello Webpack TS!')

index页面: public/index.html

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <meta http-equiv="X-UA-Compatible" content="ie=edge">
  7. <title>webpack & TS</title>
  8. </head>
  9. <body>
  10. </body>
  11. </html>

build/webpack.config.js

  1. const {CleanWebpackPlugin} = require('clean-webpack-plugin')
  2. const HtmlWebpackPlugin = require('html-webpack-plugin')
  3. const path = require('path')
  4. const isProd = process.env.NODE_ENV === 'production' // 是否生产环境
  5. function resolve (dir) {
  6. return path.resolve(__dirname, '..', dir)
  7. }
  8. module.exports = {
  9. mode: isProd ? 'production' : 'development',
  10. entry: {
  11. app: './src/main.ts'
  12. },
  13. output: {
  14. path: resolve('dist'),
  15. filename: '[name].[contenthash:8].js'
  16. },
  17. module: {
  18. rules: [
  19. {
  20. test: /\.tsx?$/,
  21. use: 'ts-loader',
  22. include: [resolve('src')]
  23. }
  24. ]
  25. },
  26. plugins: [
  27. new CleanWebpackPlugin({
  28. }),
  29. new HtmlWebpackPlugin({
  30. template: './public/index.html'
  31. })
  32. ],
  33. resolve: {
  34. extensions: ['.ts', '.tsx', '.js']
  35. },
  36. devtool: isProd ? 'cheap-module-source-map' : 'cheap-module-eval-source-map',
  37. devServer: {
  38. host: 'localhost', // 主机名
  39. stats: 'errors-only', // 打包日志输出输出错误信息
  40. port: 8081,
  41. open: true
  42. },
  43. }

配置打包命令

  1. "dev": "cross-env NODE_ENV=development webpack-dev-server --config build/webpack.config.js",
  2. "build": "cross-env NODE_ENV=production webpack --config build/webpack.config.js"

运行与打包

  1. yarn dev
  2. yarn build