使用typescript开发chrome扩展


记录一下使用typescript开发chrome扩展的相关配置。

1. 安装依赖

必定需要用到的开发依赖项:

  • chrome-types
  • copy-webpack-plugin
  • ts-loader
  • typescript
  • webpack-cli
npm install chrome-types webpack-cli ts-loader typescript copy-webpack-plugin --save-dev

2. 打包配置

2.1 首先创建ts配置文件

npx tsc --init

2.2 创建webpack打包配置文件

const path = require('path');
const CopyPlugin = require("copy-webpack-plugin");

module.exports = {
  mode: 'production',
  entry: {
    index: {
      import: './src/index.ts',
      filename: 'index.js'
    },
    background: {
      import: './src/background.ts',
      filename: 'background.js'
    }
  },
  plugins: [
    new CopyPlugin({
      patterns: [
        { from: "public", to: "" },
      ],
    }),
  ],
  module: {
    rules: [
      {
        test: /\.tsx?$/,
        use: 'ts-loader',
        exclude: /node_modules/,
      },
    ],
  },
  resolve: {
    extensions: ['.tsx', '.ts', '.js'],
  },
  output: {
    clean: true
  },
};

3. 配置打包命令

"scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "webpack build"
  }

4. 基本目录结构截图

chrome使用typescript目录结构
chrome使用typescript目录结构