gulp构建reacttypescript项目十一构建检查tsx

本文主要对以下部分进行处理;

  1. 构建tsx
  2. 路径映射
  3. eslint检查tsx

一、构建tsx

1、安装相关依赖,本文选择tsify插件来解析tsx,tsify会根据tsconfig.json配置来解析tsx,传送门:https://www.npmjs.com/package…。

cnpm i -D tsify

2、构建脚本

const _script = () => {
  return browserify({
      entries: _path.main_js,
      debug: isDev, // 生成inline-sourcemap
    }).plugin(tsify)
    .transform(babelify, {
      presets: ['@babel/preset-env', '@babel/preset-react'],
      plugins: [
        '@babel/plugin-transform-runtime', 
        ['@babel/plugin-proposal-decorators', { 'legacy': true }], 
        ['@babel/plugin-proposal-class-properties', { 'loose': true }]
      ]
    })
    .bundle()
    .pipe(gulpif(isDev, exorcist(path.resolve(__dirname, 'dist/js/app.js.map')))) // 生成外部map
    .pipe(source('app.js'))
    .pipe(buffer())
    .pipe(gulpif(isProd, uglify()))
    .pipe(gulpif(isProd, rename({suffix: '.min'})))
    .pipe(gulp.dest('./dist/js'))
    .pipe(gulpif(isDev, connect.reload()));
};

3、tsconfig.json配置

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "jsx": "react",
    "strict": true,
    "noImplicitAny": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true
  }
}

二、路径映射

路径映射需要配置两个地方,构建脚本和tsconfig.json,因为执行构建脚本时他并不知道tsconfig.json当中的路径配置,所以两个地方都需要统一配置。
1、tsconfig.json加上路径映射

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "jsx": "react",
    "strict": true,
    "noImplicitAny": true,
    "baseUrl": ".",
    "paths": {
      "components/*": ["./src/components/*"]
    }, 
    "rootDirs": ["./src"],
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true
  }
}

2、browserify配置对象的paths属性可以设置搜索的目录
传送门:https://github.com/browserify…

const _script = () => {
  return browserify({
      entries: _path.main_js,
      debug: isDev, // 生成inline-sourcemap
      extensions: ['.js', '.jsx', 'tsx', '.json'],
      paths: ['./src/'], // 是目录的数组,当查找未使用相对路径引用的模块时,浏览器会搜索这些目录。可以是绝对的,也可以是相对的basedir。等效于NODE_PATH调用browserify命令时设置环境变量。
    }).plugin(tsify)
    .transform(babelify, {
      presets: ['@babel/preset-env', '@babel/preset-react'],
      plugins: [
        '@babel/plugin-transform-runtime', 
        ['@babel/plugin-proposal-decorators', { 'legacy': true }], 
        ['@babel/plugin-proposal-class-properties', { 'loose': true }]
      ]
    })
    .bundle()
    .pipe(gulpif(isDev, exorcist(path.resolve(__dirname, 'dist/js/app.js.map')))) // 生成外部map
    .pipe(source('app.js'))
    .pipe(buffer())
    .pipe(gulpif(isProd, uglify()))
    .pipe(gulpif(isProd, rename({suffix: '.min'})))
    .pipe(gulp.dest('./dist/js'))
    .pipe(gulpif(isDev, connect.reload()));
};

注意:paths和config.json中路径配置应该保持一致,不然编译或者构建时会报错。

三、eslint检查tsx

【腾讯云】轻量 2核2G4M,首年65元

阿里云限时活动-云数据库 RDS MySQL  1核2G配置 1.88/月 速抢

本文由乐趣区整理发布,转载请注明出处,谢谢。

您可能还喜欢...

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据