GithubHelp home page GithubHelp logo

xiaoxiangmoe / vite-plugin-commonjs-externals Goto Github PK

View Code? Open in Web Editor NEW
59.0 3.0 8.0 59 KB

Add commonjs external support for vite. Mainly to provide vite support for electron.

License: MIT License

TypeScript 76.15% JavaScript 23.85%
vite-plugin electron commonjs

vite-plugin-commonjs-externals's Introduction

vite-plugin-commonjs-externals npm

Provides commonjs externals support for Vite.

Description

Prevent bundling of certain esm imported packages and instead retrieve these external dependencies at runtime by commonjs require.

For example:

import commonjsExternals from 'vite-plugin-commonjs-externals';

const externals = ['path', /^electron(\/.+)?$/];

export default {
  optimizeDeps: {
    exclude: externals,
  },
  plugins: commonjsExternals({
    externals,
  }),
};

This will convert it

import fs from 'fs';
import * as path from 'path';
import e1 from 'electron';
import e2, * as e3 from 'electron/main';

console.log({ fs, path, e1, e2, e3 });

to

import * as fs from 'fs';
const path = (() => {
  const mod = require('path');
  return mod?.__esModule
    ? mod
    : Object.assign(Object.create(null), mod, {
        default: mod,
        [Symbol.toStringTag]: 'Module',
      });
})();
const { default: e1 } = (() => {
  const mod = require('electron');
  return mod?.__esModule
    ? mod
    : Object.assign(Object.create(null), mod, {
        default: mod,
        [Symbol.toStringTag]: 'Module',
      });
})();
const e3 = (() => {
  const mod = require('electron/main');
  return mod?.__esModule
    ? mod
    : Object.assign(Object.create(null), mod, {
        default: mod,
        [Symbol.toStringTag]: 'Module',
      });
})();
const { default: e2 } = e3;
console.log({ fs, path, e1, e2, e3 });

React + Electron renderer Config Example

// vite.config.ts
import { defineConfig } from 'vite';
import { escapeRegExp } from 'lodash';
import reactRefresh from '@vitejs/plugin-react-refresh';
import builtinModules from 'builtin-modules';
// For two package.json structure
import pkg from '../the-path-to-main-process-dir/package.json';
// For single package.json structure
import pkg from './package.json';
import commonjsExternals from 'vite-plugin-commonjs-externals';

const commonjsPackages = [
  'electron',
  'electron/main',
  'electron/common',
  'electron/renderer',
  'original-fs',
  ...builtinModules,
  ...Object.keys(pkg.dependencies).map(
    name => new RegExp('^' + escapeRegExp(name) + '(\\/.+)?$')
  ),
] as const;

export default defineConfig({
  optimizeDeps: {
    exclude: commonjsPackages,
  },
  plugins: [reactRefresh(), commonjsExternals({ externals: commonjsPackages })],
});

vite-plugin-commonjs-externals's People

Contributors

dusionlike avatar sfjohnson avatar xiaoxiangmoe 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  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

Watchers

 avatar  avatar  avatar

vite-plugin-commonjs-externals's Issues

How to use it with 'node-fetch'?

I'm creating an electron app with nodeIntegration: true.

I'm using https://electron-vite.org/guide/dev.html#nodeintegration

I have this error when use "node-fetch" in my package.json

Uncaught Error Error: require() of ES Module C:\app\node_modules\.pnpm\n[email protected]\node_modules\node-fetch\src\index.js not supported.
  "dependencies": {
    "@electron-toolkit/preload": "^2.0.0",
    "@electron-toolkit/utils": "^2.0.0",
    "builtin-modules": "^3.3.0",
    "lodash": "^4.17.21",
    "node-fetch": "^3.3.2",
    "vite-plugin-commonjs-externals": "^0.1.3"
  },
import { resolve } from 'path'
import { defineConfig, externalizeDepsPlugin } from 'electron-vite'
import react from '@vitejs/plugin-react'

import lodash from 'lodash'
import commonjsExternals from 'vite-plugin-commonjs-externals'
import pkg from './package.json'

const commonjsPackages = [
  'electron',
  'electron/main',
  'electron/common',
  'electron/renderer',
  ...Object.keys(pkg.dependencies).map(
    (name) => new RegExp('^' + lodash.escapeRegExp(name) + '(\\/.+)?$')
  )
] as const

export default defineConfig({
  main: {
    plugins: [externalizeDepsPlugin()]
  },
  preload: {
    plugins: [externalizeDepsPlugin()]
  },
  renderer: {
    resolve: {
      alias: {
        '@renderer': resolve('src/renderer/src')
      }
    },
    plugins: [react(), commonjsExternals({ externals: commonjsPackages })]
  }
})

Thanks

commonjsExternals is not a function

commonjsExternals is not a function

import commonjsExternals from 'vite-plugin-commonjs-externals';
export default defineConfig({
plugins: [
vue(),
commonjsExternals({ externals: ['crypto' , 'buffer' , 'fs'] }),

],
})

Module "fs" has been externalized for browser compatibility and cannot be accessed in client code

vite config:

import vue from '@vitejs/plugin-vue';
import { defineConfig } from 'vite';
import ViteComponents from 'vite-plugin-components';
import commonjsExternals from 'vite-plugin-commonjs-externals';

import gdAntdPlusResolver from './utils/gd-ant-plus-resolver';
import builtinModules from './utils/builtin-modules';

const commonjsPackages = [
    'electron',
    'electron/main',
    'electron/common',
    'electron/renderer',
    ...builtinModules,
] as const;

// https://vitejs.dev/config/
export default defineConfig({
    plugins: [
        vue(),
        ViteComponents({
            dirs: ['components'],
            globalComponentsDeclaration: './typings/components.d.ts',
            customComponentResolvers: [
                gdAntdPlusResolver({
                    importLess: true,
                    resolveIcons: true,
                }),
            ],
        }),
        commonjsExternals({ externals: commonjsPackages }),
    ],
    css: {
        preprocessorOptions: {
            less: {
                javascriptEnabled: true,
            },
        },
    },
});

vue code:

<template>
    <div class="settings">
        <div class="settings-item">
            <label for="aeInstallationDirectory">AE 安装目录:</label>
            <span>{{ aeSdkInstallDir }}</span>
            <a-button>选择</a-button>
        </div>
    </div>
</template>

<script lang="ts" setup>
import path from 'path';
import fs from 'fs';
import util from 'util';
import { onMounted, ref } from 'vue';

console.log(fs.readFileSync);
const access = util.promisify(fs.access);
const readDir = util.promisify(fs.readdir);

async function existsFile(path: string) {
    try {
        await access(path, fs.constants.F_OK);
    } catch (error) {
        return false;
    }
    return true;
}

async function getAESdkInstallationDir() {
    const defaultApplicationDir = '/Applications';
    if (await existsFile(defaultApplicationDir)) {
        const files = await readDir(defaultApplicationDir);
        for (const file of files) {
            if (file.match(/Adobe After Effects 20\d\d/)) {
                return path.resolve(defaultApplicationDir, file);
            }
        }
    }
    return '';
}

const aeSdkInstallDir = ref('');

onMounted(async () => {
    // aeSdkInstallDir.value = await getAESdkInstallationDir();
});
</script>

<style lang="less">
.settings {
    height: 100vh;

    // &-item {

    // }
}
</style>

version info:

"electron": "^13.1.6"

image

image

Module "child_process" has been externalized for browser compatibility. Cannot access "child_process.execSync" in client code.

因为 Vite 不支持渲染进程直接调用 node 相关模块,所以借助 vite-plugin-commonjs-externals 插件绕过 vite 的编译报错问题:

import { defineConfig } from 'vite';
import commonjsExternals from 'vite-plugin-commonjs-externals';

const externals = ['path','os','fs',electron','child_process'];

export default defineConfig({
  optimizeDeps: {
    exclude: externals,
  },
  plugins: [commonjsExternals({ externals })],
});

结果编译正常,但是代码运行时报错:

import {execSync} from 'child_process';
// 直接打印 execSync 有值,不报错
console.log('execSync',execSync);

// 一运行就报错:
execSync(xxx)
image

请问该问题应该如何解决?

Error I Dont Know

<template>
  <div>App</div>
</template>

<script lang="ts">
import { defineComponent, reactive, toRefs } from "vue";
import electron from "electron";
// const { remote } = require("electron");

interface StateOption {}

export default defineComponent({
  name: "App",
  setup() {
    const state = reactive<StateOption>({});
    // console.log(remote.getCurrentWindow().id);
    console.log(electron);

    return {
      ...toRefs(state)
    };
  }
});
</script>

<style lang="scss" scoped></style>
// vite.config.ts
  plugins: [
    vue(),
    commonjsExternals({
      externals: ["path", /^electron(\/.+)?$/]
    })
  ],
index.js:4 Uncaught TypeError: path.join is not a function
    at node_modules/_electron@9.4.4@electron/index.js (index.js:4)
    at __require2 (chunk-IHTDASF6.js?v=6658ee1b:17)
    at dep:electron:1

Svelte support

Hello!

I was able to get this plugin working with Svelte by changing one line of code. Would it be possible to merge this and publish it as v0.1.4 on npm?

Here is the PR: #15

Thank you.

TypeError: commonjsExternals is not a function

With vite-plugin-commonjs-externals version ^0.1.1 and vite version ^2.6.5 I get the following error with npm run dev:

failed to load config from /home/konrad/projekte/snik/cytoscape/vite.config.js
error when starting dev server:
TypeError: commonjsExternals is not a function
    at file:///home/konrad/projekte/snik/cytoscape/vite.config.js?t=1633965357544:6:11
    at ModuleJob.run (node:internal/modules/esm/module_job:183:25)
    at async Loader.import (node:internal/modules/esm/loader:178:24)
    at async importModuleDynamicallyWrapper (node:internal/vm/module:437:15)
    at async loadConfigFromFile (/home/konrad/projekte/snik/cytoscape/node_modules/vite/dist/node/chunks/dep-55830a1a.js:68524:31)
    at async resolveConfig (/home/konrad/projekte/snik/cytoscape/node_modules/vite/dist/node/chunks/dep-55830a1a.js:68105:28)
    at async createServer (/home/konrad/projekte/snik/cytoscape/node_modules/vite/dist/node/chunks/dep-55830a1a.js:66619:20)
    at async CAC.<anonymous> (/home/konrad/projekte/snik/cytoscape/node_modules/vite/dist/node/cli.js:687:24)

vite.config.js

Following https://www.npmjs.com/package/vite-plugin-commonjs-externals, my vite.config.js is:

import commonjsExternals from 'vite-plugin-commonjs-externals';

export default {
	sourcemap: true,
	plugins: commonjsExternals({
		externals: ['path', /^level-js(\/.+)?$/],
	  }),
	build: {
		target: "es2020",
		rollupOptions: {
			output: {
				assetFileNames: "assets/[name][extname]",
			},
		},
	},
};

Plugin fails to load

I just added this plugin to my vite config, and now I get this error when running yarn dev:

$ vite
failed to load config from /home/garyo/dss/product/horizon/horizon/packages/camera-move-designer/vite.config.ts
error when starting dev server:
/home/garyo/dss/product/horizon/horizon/node_modules/vite-plugin-commonjs-externals/dist/index.js:31
        if (node?.type !== 'ImportDeclaration') {
                 ^

SyntaxError: Unexpected token '.'
    at wrapSafe (internal/modules/cjs/loader.js:915:16)
    at Module._compile (internal/modules/cjs/loader.js:963:27)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10)
    at Module.load (internal/modules/cjs/loader.js:863:32)
    at Function.Module._load (internal/modules/cjs/loader.js:708:14)
    at Module.require (internal/modules/cjs/loader.js:887:19)
    at require (internal/modules/cjs/helpers.js:74:18)
    at Object.<anonymous> (/home/garyo/dss/product/horizon/horizon/packages/camera-move-designer/vite.config.ts:35:56)
    at Module._compile (internal/modules/cjs/loader.js:999:30)
    at Object.require.extensions.<computed> [as .ts] (/home/garyo/dss/product/horizon/horizon/node_modules/vite/dist/node/chunks/dep-9f74b403.js:77249:20)

My vite.config.js:

import * as path from 'path'
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import commonjsExternals from 'vite-plugin-commonjs-externals'

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [vue(),
            commonjsExternals({externals: ['make-error-cause']})],
  resolve: {
    alias: [{find: '@', replacement: path.resolve(__dirname, '../front-end/src')}]
  },
  server: {
    fs: {
      allow: ['..']
    }
  }
})

which looks like my typescript is too old, but I have tsc --version = 'Version 4.4.3' so I don't know. I see that dist/index.js is a Javascript file, so perhaps it should not have Typescript syntax?

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.