用 TypeScript 写 webpack loader

2,178 阅读1分钟

下面以最简单的 raw-loader 为例,写一个用 TypeScript 来写一个 webpack loader.

项目初始化

  1. 在 GitHub 创建仓库 ts-raw-loader
  2. clone 项目.
  3. 进入项目目录,使用 npm 初始化项目。npm init --y
  4. 使用 tsc 初始化项目配置。 tsc --init

安装依赖

  1. 安装 TypeScript yarn add -D typescript
  2. 安装 Webpack 声明文件 yarn add -D @types/webpack

项目基本配置

tsconfig.json 配置

参考修改的配置如下,最终配置见 GitHub 仓库

{
   "compilerOptions": {
    "target": "es2016",
    "module": "commonjs",
    "outDir": "./dist",
    "declaration": true,
    "declarationDir": "./dist/types",
    "strict": true,
    "moduleResolution": "node",
    "baseUrl": "./",
    "paths": {
        "@/*": ["src/*"]
    }
},
include: ["src/**/*.ts"]
}

编写 loader 代码。

创建 src/index.ts 模块文件。代码如下:

import webpack = require("webpack");

// Taken from https://github.com/webpack-contrib/raw-loader/blob/master/index.js
// 关于为什么要将 \u2028 和 \u2029 转义,参考
// https://www.web-tinker.com/article/21252.html
export default function rawLoader(
  this: webpack.loader.LoaderContext,
  source: string | Buffer
) {
  this.value = source;
  const json = JSON.stringify(source)
    .replace(/\u2028/g, "\\u2028")
    .replace(/\u2029/g, "\\u2029");
  return `module.exports = ${json}`;
}

如上就是我们的 webpack loader ts-raw-loader 的核心代码。

写好,使用 tsc 编译好之后便可发布。 完整代码参见: GitHub 仓库