GithubHelp home page GithubHelp logo

vite-plugin / vite-plugin-optimizer Goto Github PK

View Code? Open in Web Editor NEW
33.0 0.0 2.0 48 KB

Manually Pre-Bundling of Vite

Home Page: https://www.npmjs.com/package/vite-plugin-optimizer

License: MIT License

JavaScript 100.00%

vite-plugin-optimizer's Introduction

vite-plugin-optimizer

Manually Pre-Bundling of Vite

NPM version NPM Downloads awesome-vite

English | 简体中文

  • Compatible Browser, Node.js and Electron
  • Custom Vite Pre-Bundling content

Install

npm i vite-plugin-optimizer -D

Usage

import optimizer from 'vite-plugin-optimizer'

export default {
  plugins: [
    optimizer({
      vue: `const vue = window.Vue; export { vue as default }`,
    }),
  ]
}

Load a local file

optimizer({
  // support nested module id
  // support return Promise
  '@scope/name': () => require('fs/promises').readFile('path', 'utf-8'),
})

Node.js and Electron

optimizer({
  // optimize Electron for using `ipcRenderer` in Electron-Renderer
  electron: `const { ipcRenderer } = require('electron'); export { ipcRenderer };`,

  // this means that both 'fs' and 'node:fs' are supported
  // e.g.
  //   `import fs from 'fs'`
  //   or
  //   `import fs from 'node:fs'`
  fs: () => ({
    // this is consistent with the `alias` behavior
    find: /^(node:)?fs$/,
    code: `const fs = require('fs'); export { fs as default };`
  }),
})

Advance

Optimize Node.js ESM packages as CommonJs modules for Node.js/Electron.
e.g. execa, node-fetch

You can see 👉 vite-plugin-esmodule

API (Define)

optimizer(entries[, options])

function optimizer(entries: Entries, options?: OptimizerOptions): import('vite').Plugin;
export interface OptimizerArgs {
  /** Generated file cache directory */
  dir: string;
}

export interface ResultDescription {
  /**
   * This is consistent with the `alias` behavior.
   * 
   * e.g.  
   *   `import fs from 'fs'`  
   *   or  
   *   `import fs from 'node:fs'`  
   * 
   * @example
   * {
   *   // This means that both 'fs' and 'node:fs' are supported.
   *   find: /^(node:)?fs$/,
   *   replacement: '/project/node_modules/.vite-plugin-optimizer/fs.js',
   * }
   */
  alias?: {
    find: string | RegExp;
    /**
     * If not explicitly specified, will use the path to the generated file as the default.
     */
    replacement?: string;
  };
  code?: string;
}

export interface Entries {
  [moduleId: string]:
  | string
  | ResultDescription
  | ((args: OptimizerArgs) => string | ResultDescription | Promise<string | ResultDescription | void> | void);
}

export interface OptimizerOptions {
  /**
   * @default ".vite-plugin-optimizer"
   */
  dir?: string;
  resolveId?: ((id: string) => string | Promise<string | void> | void);
}

How to work

Let's use Vue as an example

optimizer({
  vue: `const vue = window.Vue; export { vue as default }`,
})
  1. Create node_modules/.vite-plugin-optimizer/vue.js and contains the following code
const vue = window.Vue; export { vue as default }
  1. Register a vue alias item and add it to resolve.alias
{
  resolve: {
    alias: [
      {
        find: 'vue',
        replacement: '/User/work-directory/node_modules/.vite-plugin-optimizer/vue',
      },
    ],
  },
}

/**
 * 🚧
 * If you are using a function and have no return value, alias will not be registered.
 * In this case, you must explicitly specify alias.
 * 
 * e.g.
 * 
 * optimizer({
 *   async vue(args) {
 * 
 *     // ① You can customize the build `vue` and output it to the specified folder.
 *     await require('vite').build({
 *       entry: require.resolve('vue'),
 *       outputDir: args.dir + '/vue',
 *     })
 * 
 *     return {
 *       alias: {
 *         find: 'vue',
 *         // ② Make sure `replacement` points to the `vue` outputDir
 *         replacement: args.dir + '/vue',
 *       }
 *     }
 *   },
 * })
 */
  1. Add vue to the optimizeDeps.exclude by default.
export default {
  optimizeDeps: {
    // 🚧 You can avoid this behavior by `optimizeDeps.include`
    exclude: ['vue'],
  },
}

vite-plugin-optimizer's People

Contributors

caoxiemeihao avatar charleewa avatar learnsomesome avatar yejimeiming avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

vite-plugin-optimizer's Issues

vite.config.ts引用失败

There are types at 'electron-project/node_modules/vite-plugin-optimizer/index.d.ts', but this result could not be resolved when respecting package.json "exports". The 'vite-plugin-optimizer' library may need to update its package.json or typings

vite4 require is not defined

vite4 require is not defined when this plugin is configured , this is my `vite.config.ts

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'

import optimizer from "vite-plugin-optimizer";

let getReplacer = () => {
  let externalModels = ["os", "fs", "path", "events", "child_process", "crypto", "http", "buffer", "url", "better-sqlite3", "knex", "stream"];
  let result = {};
  for (let item of externalModels) {
    result[item] = () => ({
      find: new RegExp(`^${item}$`),
      code: `const ${item} = require('${item}');export { ${item} as default }`,
    });
  }
  return result;
};

export default defineConfig({
  plugins: [
    optimizer(getReplacer()),
    vue()
  ],
})

When vite config resolve.alias is array have a bug

if (typeof config.resolve.alias === 'object') {
config.resolve.alias = Object
.entries(config.resolve.alias)
.reduce((memo, [find, replacement]) => memo.concat({ find, replacement }), []);
}

In your code, when resolve.alias is array,resolve.alias will be inoperative

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.