Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

React, Uncaught ReferenceError: process is not defined #9186

Closed
0sama opened this issue Jul 18, 2022 · 3 comments
Closed

React, Uncaught ReferenceError: process is not defined #9186

0sama opened this issue Jul 18, 2022 · 3 comments
Labels
invalid This doesn't seem right

Comments

@0sama
Copy link

0sama commented Jul 18, 2022

Describe the bug

After upgrading to v3 from v2.9 process.env got removed in library mode, defining new variables won't fix the issue.

in dev-mode everything works fine, this only occurs on production build.
react18 entry file in node-modules tries to access process.env.NODE_ENV which causes this issue
due to my requirements, I also can't use react as an external package.

Screenshot 2022-07-18 at 12 18 00

this is my config file:

import react from '@vitejs/plugin-react';
import { defineConfig, loadEnv } from 'vite';
import svgrPlugin from 'vite-plugin-svgr';
const { resolve } = require('path');

export default defineConfig(({ mode }) => {
  const env = loadEnv(mode, process.cwd(), '')

  return {

    // define: { // none of the below works!
    //   'process.env': {}
    //   'process.env': JSON.stringify(env),
    //   'process.env.NODE_ENV': 'production',
    // },
    plugins: [
      react(),
      svgrPlugin({
        svgrOptions: { // ...svgr options (https://react-svgr.com/docs/options/)
          icon: true,
        },
      }),
    ],
    build: {
      sourcemap:true,
      // build as a library
      lib: {
        entry: resolve(__dirname, env.ENTRY === 'desktop' ? 'src/desktop/DesktopEntry.jsx' : 'src/mobile/MobileEntry.jsx'),
        name: 'fitting-station',
        fileName: (format) => `fs-${format}.js`,
      },
    },
    resolve: {
      alias: {
        '@helpers': resolve(__dirname, 'src/common/utils/helpers.js'),
        '@style': resolve(__dirname, 'src/common/components/Style.jsx'),
        '@globalActions': resolve(__dirname, 'src/common/redux/store/actions/globalActions.js'),
        '@icons': resolve(__dirname, 'src/common/assets/icons/index.js'),
      },
    },
    server: {
      port: 3000,
      hmr: { clientPort: 3000 },
      strictPort: true, 
    }
  };
});

Reproduction

yarn build and then

cd external-project
yarn install
yarn start

the vite web-component is not loaded and will give the error in the console.

https://stackblitz.com/edit/vitejs-vite-jkfrgb?file=index.html,external-project%2Fsrc%2FApp.js,external-project%2Fpublic%2Findex.html,src%2FLayoutProvider.jsx&terminal=dev

System Info

System:
    OS: macOS 12.3.1
    CPU: (12) x64 Intel(R) Core(TM) i7-9750H CPU @ 2.60GHz
    Memory: 5.97 GB / 32.00 GB
    Shell: 3.2.57 - /bin/bash
  Binaries:
    Node: 18.0.0 - /usr/local/bin/node
    Yarn: 1.22.18 - /usr/local/bin/yarn
    npm: 8.6.0 - /usr/local/bin/npm
  Browsers:
    Chrome: 103.0.5060.114
    Firefox: 100.0
    Safari: 15.4
  npmPackages:
    @vitejs/plugin-react: ^2 => 2.0.0 
    vite: ^3.0 => 3.0.1

Used Package Manager

yarn

Logs

Click to expand!
vite:config bundled config file loaded in 128.82ms +0ms
  vite:config using resolved config: {
  vite:config   plugins: [
  vite:config     'vite:build-metadata',
  vite:config     'vite:pre-alias',
  vite:config     'alias',
  vite:config     'vite:react-babel',
  vite:config     'vite:react-refresh',
  vite:config     'vite:react-jsx',
  vite:config     'vite:modulepreload-polyfill',
  vite:config     'vite:resolve',
  vite:config     'vite:html-inline-proxy',
  vite:config     'vite:css',
  vite:config     'vite:esbuild',
  vite:config     'vite:json',
  vite:config     'vite:wasm-helper',
  vite:config     'vite:worker',
  vite:config     'vite:asset',
  vite:config     'vite-plugin-svgr',
  vite:config     'vite:wasm-fallback',
  vite:config     'vite:define',
  vite:config     'vite:css-post',
  vite:config     'vite:build-html',
  vite:config     'vite:worker-import-meta-url',
  vite:config     'vite:watch-package-data',
  vite:config     'commonjs',
  vite:config     'vite:data-uri',
  vite:config     'vite:asset-import-meta-url',
  vite:config     'vite:dynamic-import-vars',
  vite:config     'vite:import-glob',
  vite:config     'custom-hmr',
  vite:config     'vite:build-import-analysis',
  vite:config     'vite:esbuild-transpile',
  vite:config     'vite:terser',
  vite:config     'vite:reporter',
  vite:config     'vite:load-fallback'
  vite:config   ],
  vite:config   build: {
  vite:config     target: [ 'es2020', 'edge88', 'firefox78', 'chrome87', 'safari13' ],
  vite:config     polyfillModulePreload: true,
  vite:config     outDir: 'dist',
  vite:config     assetsDir: 'assets',
  vite:config     assetsInlineLimit: 4096,
  vite:config     cssCodeSplit: false,
  vite:config     cssTarget: [ 'es2020', 'edge88', 'firefox78', 'chrome87', 'safari13' ],
  vite:config     sourcemap: true,
  vite:config     rollupOptions: {},
  vite:config     minify: 'esbuild',
  vite:config     terserOptions: {},
  vite:config     write: true,
  vite:config     emptyOutDir: null,
  vite:config     manifest: false,
  vite:config     lib: {
  vite:config       entry: '/Users/osama.rashid/development/fitting-station-web-component/src/mobile/MobileEntry.jsx',
  vite:config       name: 'fitting-station',
  vite:config       fileName: [Function: fileName]
  vite:config     },
  vite:config     ssr: false,
  vite:config     ssrManifest: false,
  vite:config     reportCompressedSize: true,
  vite:config     chunkSizeWarningLimit: 500,
  vite:config     watch: null,
  vite:config     commonjsOptions: { include: [Array], extensions: [Array] },
  vite:config     dynamicImportVarsOptions: { warnOnError: true, exclude: [Array] }
  vite:config   },
  vite:config   resolve: {
  vite:config     alias: [ [Object], [Object], [Object], [Object], [Object], [Object] ],
  vite:config     dedupe: [ 'react', 'react-dom' ]
  vite:config   },
  vite:config   server: {
  vite:config     preTransformRequests: true,
  vite:config     port: 3000,
  vite:config     hmr: { clientPort: 3000 },
  vite:config     strictPort: true,
  vite:config     middlewareMode: false,
  vite:config     fs: { strict: true, allow: [Array], deny: [Array] }
  vite:config   },
  vite:config   optimizeDeps: {
  vite:config     disabled: 'build',
  vite:config     force: undefined,
  vite:config     include: [ 'react/jsx-runtime', 'react/jsx-dev-runtime' ],
  vite:config     esbuildOptions: { preserveSymlinks: undefined }
  vite:config   },
  vite:config   configFile: '/Users/osama.rashid/development/fitting-station-web-component/vite.config.js',
  vite:config   configFileDependencies: [
  vite:config     '/Users/osama.rashid/development/fitting-station-web-component/viteSassWatcher.js',
  vite:config     '/Users/osama.rashid/development/fitting-station-web-component/vite.config.js'
  vite:config   ],
  vite:config   inlineConfig: {
  vite:config     root: undefined,
  vite:config     base: undefined,
  vite:config     mode: undefined,
  vite:config     configFile: undefined,
  vite:config     logLevel: undefined,
  vite:config     clearScreen: undefined,
  vite:config     optimizeDeps: { force: undefined },
  vite:config     build: {}
  vite:config   },
  vite:config   root: '/Users/osama.rashid/development/fitting-station-web-component',
  vite:config   base: '/',
  vite:config   publicDir: '/Users/osama.rashid/development/fitting-station-web-component/public',
  vite:config   cacheDir: '/Users/osama.rashid/development/fitting-station-web-component/node_modules/.vite',
  vite:config   command: 'build',
  vite:config   mode: 'production',
  vite:config   ssr: {
  vite:config     format: 'esm',
  vite:config     target: 'node',
  vite:config     optimizeDeps: { disabled: true, esbuildOptions: [Object] }
  vite:config   },
  vite:config   isWorker: false,
  vite:config   mainConfig: null,
  vite:config   isProduction: true,
  vite:config   preview: {
  vite:config     port: undefined,
  vite:config     strictPort: true,
  vite:config     host: undefined,
  vite:config     https: undefined,
  vite:config     open: undefined,
  vite:config     proxy: undefined,
  vite:config     cors: undefined,
  vite:config     headers: undefined
  vite:config   },
  vite:config   env: { BASE_URL: '/', MODE: 'production', DEV: false, PROD: true },
  vite:config   assetsInclude: [Function: assetsInclude],
  vite:config   logger: {
  vite:config     hasWarned: false,
  vite:config     info: [Function: info],
  vite:config     warn: [Function: warn],
  vite:config     warnOnce: [Function: warnOnce],
  vite:config     error: [Function: error],
  vite:config     clearScreen: [Function: clearScreen],
  vite:config     hasErrorLogged: [Function: hasErrorLogged]
  vite:config   },
  vite:config   packageCache: Map(0) { set: [Function (anonymous)] },
  vite:config   createResolver: [Function: createResolver],
  vite:config   worker: {
  vite:config     format: 'iife',
  vite:config     plugins: [
  vite:config       [Object], [Object], [Object],
  vite:config       [Object], [Object], [Object],
  vite:config       [Object], [Object], [Object],
  vite:config       [Object], [Object], [Object],
  vite:config       [Object], [Object], [Object],
  vite:config       [Object], [Object], [Object],
  vite:config       [Object], [Object], [Object],
  vite:config       [Object], [Object], [Object],
  vite:config       [Object], [Object], [Object],
  vite:config       [Object]
  vite:config     ],
  vite:config     rollupOptions: {}
  vite:config   },
  vite:config   appType: 'spa',
  vite:config   experimental: { importGlobRestoreExtension: false, hmrPartialAccept: false }
  vite:config } +16ms```
</details>

### Validations

- [X] Follow our [Code of Conduct](https://github.com/vitejs/vite/blob/main/CODE_OF_CONDUCT.md)
- [X] Read the [Contributing Guidelines](https://github.com/vitejs/vite/blob/main/CONTRIBUTING.md).
- [X] Read the [docs](https://vitejs.dev/guide).
- [X] Check that there isn't [already an issue](https://github.com/vitejs/vite/issues) that reports the same bug to avoid creating a duplicate.
- [X] Make sure this is a Vite issue and not a framework-specific issue. For example, if it's a Vue SFC related bug, it should likely be reported to [vuejs/core](https://github.com/vuejs/core) instead.
- [X] Check that this is a concrete bug. For Q&A open a [GitHub Discussion](https://github.com/vitejs/vite/discussions) or join our [Discord Chat Server](https://chat.vitejs.dev/).
- [X] The provided reproduction is a [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example) of the bug.
@github-actions
Copy link

Hello @osama996. Please provide a minimal reproduction using a GitHub repository or StackBlitz. Issues marked with need reproduction will be closed if they have no activity within 3 days.

@0sama 0sama changed the title React, Uncaught ReferenceError: process is not defined index.js React, Uncaught ReferenceError: process is not defined Jul 18, 2022
@fila90
Copy link

fila90 commented Jul 19, 2022

I'm having this same issue
Using Vite with cypress, I'm parsing the files in lib mode, and the same error comes up

      on('file:preprocessor', async (file) => {
        const { filePath, outputPath } = file;
        const filename = path.basename(outputPath);
        const filenameWithoutExtension = path.basename(outputPath, path.extname(outputPath));

        const viteConfig = {
          jsx: 'react',
          plugins: [flowPlugin(), react()],
          build: {
            emptyOutDir: false,
            minify: false,
            outDir: path.dirname(outputPath),
            sourcemap: true,
            write: true,
          },
        };

        if (filename.endsWith('.html')) {
          viteConfig.build.rollupOptions = {
            input: {
              [filenameWithoutExtension]: filePath,
            },
          };
        } else {
          viteConfig.build.lib = {
            entry: filePath,
            fileName: () => filename,
            formats: ['es'],
            name: filenameWithoutExtension,
          };
        }

        await vite.build(viteConfig);
        return outputPath;
      });

@sapphi-red
Copy link
Member

production needs to be wrapped with double-quotes. See docs.

    define: {
      'process.env.NODE_ENV': '"production"'
    },

@sapphi-red sapphi-red added invalid This doesn't seem right and removed pending triage labels Jul 19, 2022
@github-actions github-actions bot locked and limited conversation to collaborators Aug 3, 2022
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
invalid This doesn't seem right
Projects
None yet
Development

No branches or pull requests

4 participants