Socket
Socket
Sign inDemoInstall

vite-file-import-transform

Package Overview
Dependencies
33
Maintainers
1
Versions
2
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

    vite-file-import-transform

`require('xxxx')` to `new URL('xxxx', import.meta.url).href`


Version published
Maintainers
1
Created

Readme

Source

Vite-file-import-transform

项目打包替换为vite时,需要引入依赖代码转es module的库,但这类库通常不会替换项目中const img = require("@/assets/xxxx.jpg")的写法。

vite官方推荐将其替换为new URL('@/assets/xxxx.jpg', import.meta.url).href的写法,参考地址

本插件即是自动将require的写法替换成new URL的写法

配置和用法

配置如下:

import * as t from "@babel/types";

interface viteFileImportTransformParams {
  include?: RegExp|RegExp[];
  exclude?: RegExp|RegExp[];
  // 假设require('./xxx.jpg'), filePath即是'./xxx.jpg'对应的ast树节点,若函数返回null,则不转换
  // 该函数用于细化控制转换内容
  importPathHandler?: (filePath: t.StringLiteral|t.TemplateLiteral) => t.StringLiteral|t.TemplateLiteral|null;
}

用法:

import { defineConfig } from "vite";
import viteFileImportTransform from "vite-file-import-transform";

const config = defineConfig({
  plugins: [
    viteFileImportTransform({
      // 假设只针对node_modules下的xxx库
      // include、exclude传入格式为: RegExp[]
      include: [/\.tsx?$/], // include不穿的话默认是匹配.ts和.tsx
      exclude: [],
      importPathHandler: ()=>{}
    })
  ]
})

export default config;

Keywords

FAQs

Last updated on 06 May 2023

Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc