npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

upload-assets-to-cdn

v0.1.0

Published

A powerful nodejs plugin which can help you to upload assets into cdn

Downloads

3

Readme

介绍

GitHub Repo stars npm (scoped) GitHub tag

一个帮助你上传静态资源到 CDN 的插件,上传成功后用 CDN 地址自动替换掉源代码引用,默认支持静态资源压缩

功能

  • 支持 阿里云、腾讯云、七牛云等等 oss 客户端,支持普通 http 文件上传接口
  • 支持 png | jpg | jpeg | gif | svg | bmp | webp 格式的静态资源,可自定义需要上传的静态资源
  • 支持静态资源压缩、压缩日志、自定义压缩配置
  • 支持解析通过 alias 引用的静态资源
  • 支持任何前端构建工具环境使用
  • 支持静态资源上传结果缓存,避免重复上传
  • 支持上传成功后,同步删除本地的静态资源

使用

# npm
npm i upload-assets-to-cdn --save-dev

# pnpm
pnpm i upload-assets-to-cdn -D

通过 oss 客户端进行上传

项目根目录新建 upload-assets-to-cdn.config.mjs

import OSS from 'ali-oss';
import crypto from 'node:crypto';
import path from 'node:path';
import uploadAssetsToCdn from 'upload-assets-to-cdn';

const client = new OSS({
  region: 'oss-cn-shanghai',
  bucket: 'my-pic-lib',
  accessKeyId: '',
  accessKeySecret: '',
});

uploadAssetsToCdn({
  async upload({ fileSource, fileName }) {
    const fileExtName = path.extname(fileName);
    const basicFileName = path.basename(fileName, fileExtName);
    const fileMD5Name = crypto
      .createHash('md5')
      .update(basicFileName)
      .digest('hex');

    return client.put(`project-xxxx/${fileMD5Name}`, fileSource);
  },
});

package.jsonscript 中添加命令: "upload-assets-to-cdn": "node ./upload-assets-to-cdn.config.mjs"

生成结果:

npm run upload-assets-to-cdn

通过 http 文件上传接口进行上传

项目根目录新建 upload-assets-to-cdn.config.cjs

const axios = require('axios');
const FormData = require('form-data');
const crypto = require('node:crypto');
const path = require('node:path');

uploadAssetsToCdn({
  async upload({ fileSource, fileName, fileType, filePath }) {
    const fileExt = path.extname(fileName);
    const basicFileName = path.basename(fileName, fileExt);
    const fileMD5Name = crypto
      .createHash('md5')
      .update(basicFileName)
      .digest('hex');

    const formData = new FormData();
    formData.append('systemCode', 'PHARMACY');
    formData.append('belongCode', 'RP');
    formData.append('belongID', fileMD5Name);
    formData.append('file', fileSource, {
      filename: fileName,
      contentType: fileType,
    });

    try {
      const response = await axios.post(
        'https://file.xxxxxxx.com/api/upload/file',
        formData,
        {
          headers: {
            'Content-Type': 'multipart/form-data',
          },
        }
      );

      if (response?.data?.data?.remoteAddress) {
        return { url: response?.data?.data?.remoteAddress };
      }

      return { url: '' };
    } catch (error) {
      console.error('Error uploading file:', error);
      return { url: '' };
    }
  },
});

package.jsonscript 中添加命令: "upload-assets-to-cdn": "node ./upload-assets-to-cdn.config.cjs"

生成结果:

npm run upload-assets-to-cdn

参数

| 属性 | 必填 | 类型 | 默认值 | 说明 | | --- | --- | --- | --- | --- | | upload | 是 | (uploadItem: IUploadItem) => Promise<{ url: string }> | - | 自定义如何上传文件 | | exclude | 否 | RegExp | string | string[] | - | 自定义需要排除的静态资源,例如:"@/assets/logo.png" | | isLog | 否 | boolean | true | 是否启用上传日志 | | isCache | 否 | boolean | true | 是否缓存已上传的静态资源 | | isCompress | 否 | boolean | true | 是否启用静态资源压缩功能 | | isDeleteOriginAsset | 否 | boolean | false | 上传成功后,是否删除原始的静态资源文件 | | alias | 否 | Record<string, string> | { '@': './src' } | 别名规则 | | compressOptions | 否 | Record<"png" | "jpg" | "jpeg" | "gif" | "webp", PngOptions | JpegOptions | GifOptions | WebpOptions> | - | sharp静态资源压缩配置参数 | | excludeCompressFileType | 否 | string[] | ['svg', 'bmp'] | 自定义不需要压缩的静态资源类型 | | globbyPatternStr | 否 | string | 'src/*/.{js,jsx,ts,tsx,vue,css,less,scss,sass}' | 待扫描文件的匹配规则 | | assetPattern | 否 | RegExp | '.{png,jpg,jpeg,gif,svg,bmp,webp}' | 自定义需要上传的静态资源 | | sourceCodeDirectory | 否 | string | 'src' | 自定义应用源代码目录 |

FAQ

为什么在 jsx 文件中无法正常工作,如何兼容?

由于在 jsx 文件中,不支持 <img src="../assets/logo.png" /> 这种相对路径引入静态资源的方式,所以通常会使用 import Logo from '../assets/logo.png' 这种方式引入静态资源,使用该插件自动上传 CDN 后,代码会变成 import Logo from 'https://cdn.xxxx.com/logo.png',这样就会造成代码错误,所以 React 项目中,要想该插件能正常使用,你需要改变静态资源引入方式为:<img src="src/assets/logo.png" />,或者你手动将import Logo from 'https://cdn.xxxx.com/logo.png'中的 CDN 地址回填到代码对应的引用中

贡献

环境要求

  • node 18+
  • pnpm 9+

提交 Pull Request

  1. 熟悉 Pull Request 规范
  2. fork 此仓库
  3. 开一个新分支修改代码:git checkout -b my-branch main
  4. 确保你的代码可以通过所有测试用例(新增功能需要添加新的功能测试用例):pnpm test
  5. 创建 changeset 文件通过命令:pnpm changeset
  6. 使用 commit 提交你的修改(需遵循 commitlint 规范)
  7. 发起 Pull Request

License

MIT