1. 程式人生 > 實用技巧 >Webpack + Typescript打包

Webpack + Typescript打包

安裝npm

建立專案

npm init -y

安裝typescript

# ts-loader為webpack外掛
npm install --save-dev typescript ts-loader

配置tsconfig.json

{
  "compilerOptions": {
    "outDir": "./build/",
     /* 開啟source map,利於除錯 */
    "sourceMap": true,
    "module": "commonjs",
    "noImplicitAny": true,
    "target": "es5",
    "allowJs": true
  }
}

安裝webpack

npm install webpack webpack-cli --save-dev

配置webpack.config.js

const path = require('path');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const { CleanWebpackPlugin } = require("clean-webpack-plugin");

module.exports = {
  // 配置多個入口
  entry: {
    BaseInfo: './ts/src/BaseInfo.ts',
    RandomData: '/ts/src/RandomData.ts'
  },
  // 配置source-map,方便除錯
  devtool: 'inline-source-map',
  module: {
    rules: [
      {
        // 正則:查出所有ts、tsx結尾的檔案
        test: /\.tsx?$/,
        // 配置ts-loader
        use: 'ts-loader',
        // 正則:過濾node_modules
        exclude: /node_modules/
      }
    ]
  },
  plugins: [
    // clean-webpack-plugin外掛,用於每次打包都清理舊的資料
    new CleanWebpackPlugin(),
    // copy-webpack-plugin,把指定的資料夾內容複製到指定目錄
    new CopyWebpackPlugin({
      patterns: [
        {
          from: path.resolve(__dirname, 'html'),
          to: path.resolve(__dirname, 'build')
        },
      ],
    }),
  ],
  resolve: {
    extensions: ['.tsx', '.ts', '.js']
  },
  // 指定出口
  output: {
    filename: '[name]-bundle.js',
    path: path.resolve(__dirname, 'build')
  }
};