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

vite-plugin-require-transform-with-convert

v1.0.0

Published

A plugin for vite that convert from require syntax to import that compat for es module.

Downloads

462

Readme

vite-plugin-require-transform

NPM

npm version A vite plugin that converts the code from require syntax to import

Why vite-plugin-require-transform

"require syntax" is supported when develop with Webpack cause it transformed it internally.

but when serve with Vite error "require is not defined" will show up.

This plugin amis to support require when serve with vite.

Install

yarn add -D vite-plugin-require-transform

or

npm i vite-plugin-require-transform --save-dev

Usage

// vite.config.(t|j)s

import { defineConfig } from 'vite';

/**
 * @param match
 * Regular expression in string or Regexp type,
 *  or a match predicate  (this: vite transform context, code: string, id: file name string) => void
 * @returns transformed code
 */
import requireTransform from 'vite-plugin-require-transform';

export default defineConfig({
  plugins: [
    // passing string type Regular expression
    requireTransform({}),
  ],
});


// check the vite-plugin-require-transform params'type 
export type VitePluginRequireTransformParamsType = {
	//filter files that should enter the plugin
	fileRegex?: RegExp = /.ts$|.tsx$/ ,
	//prefix that would plugin into the requireSpecifier 
	importPrefix? = '_vite_plugin_require_transform_': string,
	//to deal with the requireSpecifier
	importPathHandler?: Function
}

What vite-plugin-require-transform actually do

you can also check the test directory to see the cases.

case 1:

const case1 = require("case1");
console.log("case1", case1)

will be transformed into

import _vite_plugin_require_transform_case1 from "case1";
const case1 = _vite_plugin_require_transform_case1;
console.log("case1", case1);

case 2:

example A

const case2A = location.host == 'test' ? null : require("case2");

if(location.host == 'test1' ){
    case2A.start();
}

case2A.stop();

will be transformed into

import { start as _vite_plugin_require_transform_case2start, stop as _vite_plugin_require_transform_case2stop } from "case2";
const _vite_plugin_require_transform_case2 = {
  start: _vite_plugin_require_transform_case2start,
  stop: _vite_plugin_require_transform_case2stop
};
const case2A = location.host == 'test' ? null : _vite_plugin_require_transform_case2;

if (location.host == 'test1') {
  case2A.start();
}

case2A.stop();

example B

const case2B = {
    test:require('test2B').Something
}

will be transformed into

import { Something as _vite_plugin_require_transform_test2BSomething } from "test2B";
const case2B = {
  test: _vite_plugin_require_transform_test2BSomething
};

example C

const case2c =require('test2C')


case2c.forEach((item)=>{
    console.log('item',item)
})

will be transformed into

import _vite_plugin_require_transform_test2C from "test2C";
const case2c = _vite_plugin_require_transform_test2C;
case2c.forEach(item => {
  console.log('item', item);
});

case 3:

when exist a case as same fileName,different extensions,by default it would be error cause the plugin only capture the path without extension.


//same path,different extension
const testCaseA = require("caseA.extA?aaa");
const testCaseB = require("caseA.extB?bbb");

console.log("caseA", testCaseA)
console.log("caseB", testCaseB)

so we need to make a importPathHandler to deal with the situtation

//check out __test__/index
glob("__test__/case3/*.ts", {
    ignore: "**/*transformed_result.ts"
}, async (err, files) => {
    for (const file of files) {
        const fileContent = readFileSync(file, 'utf-8');
        const transformedContent = await vitePluginRequireTransform(
            {
                importPathHandler: (requirePath: string) => {
                    return requirePath.replace('.', '_').replace('?', "_");
                }
            }
        ).transform(fileContent, file);
        writeFileSync(file.replace('.ts', '_transformed_result.ts'), transformedContent.code);
    }
})  

will be transformed into

import _vite_plugin_require_transform_caseA_extB_bbb from "caseA.extB?bbb";
import _vite_plugin_require_transform_caseA_extA_aaa from "caseA.extA?aaa";
//same path,different extension
const testCaseA = _vite_plugin_require_transform_caseA_extA_aaa;
const testCaseB = _vite_plugin_require_transform_caseA_extB_bbb;
console.log("caseA", testCaseA);
console.log("caseB", testCaseB);