Git Product home page Git Product logo

Comments (18)

sodatea avatar sodatea commented on June 12, 2024 11

Use resolve.alias, and use an ESM-compiled CDN such as skypack.dev.

A working config:

import { defineConfig } from 'vite'
import reactRefresh from '@vitejs/plugin-react-refresh'

// https://vitejs.dev/config/
export default defineConfig({
  resolve: {
    alias: {
      'react': 'https://cdn.skypack.dev/react@17',
      'react-dom': 'https://cdn.skypack.dev/react-dom@17'
    }
  },
  plugins: [reactRefresh()]
});

rollupOptions.external and rollupOptions.output.globals are not suitable for this use case, unless you are only building for legacy browsers, targeting cjs in lib output, or bundling for SSR.

from vite-plugin-react.

sodatea avatar sodatea commented on June 12, 2024 3

Then, please check out https://github.com/eight04/rollup-plugin-external-globals

from vite-plugin-react.

cixing avatar cixing commented on June 12, 2024 3

Then, please check out https://github.com/eight04/rollup-plugin-external-globals

还是一样的

from vite-plugin-react.

jansepke avatar jansepke commented on June 12, 2024 2

@sodatea but resolve.alias does not allow referencing React available gloally as window.React. This is the behavior Webpack externals supports and is necessary if you are building an app that is part of a microfrontend where React is globally available to all microapps. Is there another way of referencing a dependency that is defined on the global window object? This is only necessary for a production build, but this would not be a problem with conditional vite config.

from vite-plugin-react.

vfasky avatar vfasky commented on June 12, 2024 2

You can try https://github.com/MMF-FE/vite-plugin-cdn-import

from vite-plugin-react.

fengxinming avatar fengxinming commented on June 12, 2024 2

try this way vite-plugin-external

from vite-plugin-react.

sodatea avatar sodatea commented on June 12, 2024 1

resolve.alias is the recommended way to use CDN links in vite.

If you want to only use CDN links in production, you can configure the alias field conditionally.

References:

from vite-plugin-react.

ArnaudBarre avatar ArnaudBarre commented on June 12, 2024 1

Hi everyone.

I looking at all the open issues to see how to fix them in the next minor/major version. This issue is unactionable for me. There is no stackblitz repro and some people seems to get this working via a plugin.

If you think your usecase is still not covered, please provide a small reproduction via stackblitz

from vite-plugin-react.

ArnaudBarre avatar ArnaudBarre commented on June 12, 2024 1

Hi I looked at it and yeah this not how it works. Vite outputs ESM by default, so you need to map the imports.

I think the solution closest to you need is https://github.com/MMF-FE/vite-plugin-cdn-import suggested here: #3 (comment)

from vite-plugin-react.

jansepke avatar jansepke commented on June 12, 2024

I also have the same error with vite 2.2.3 using a project created with npm init @vitejs/app --template react vite-test without other changes.

vite config:

import { defineConfig } from "vite";
import reactRefresh from "@vitejs/plugin-react-refresh";
export default defineConfig({
  plugins: [reactRefresh()],
  build: {
    rollupOptions: {
      external: ["react", "react-dom"],
      output: {
        globals: {
          react: "React",
          "react-dom": "ReactDOM",
        },
      },
    },
  },
});

and loading react + react-dom from official CDN

from vite-plugin-react.

ckken avatar ckken commented on June 12, 2024

mark & same here

from vite-plugin-react.

ckken avatar ckken commented on June 12, 2024

场景不一样 external可以支持 远程引用而不改变当前逻辑

from vite-plugin-react.

jansepke avatar jansepke commented on June 12, 2024

Thank you, that solved my problem, maybe I got confused by the fact that rollup external is different to webpack. The Plugin works perfectly.

from vite-plugin-react.

jamesg1 avatar jamesg1 commented on June 12, 2024

Then, please check out https://github.com/eight04/rollup-plugin-external-globals

Hi I am trying to make React and ReactDom load as external deps as I load multiple vite apps on the page (non-spa). Do I need this plugin to complete the substitution of React to window.React and exclude react from any moduling/optimisations? Then i can just load react via umd?

from vite-plugin-react.

aztack avatar aztack commented on June 12, 2024

Use resolve.alias, and use an ESM-compiled CDN such as skypack.dev.

A working config:

import { defineConfig } from 'vite'
import reactRefresh from '@vitejs/plugin-react-refresh'

// https://vitejs.dev/config/
export default defineConfig({
  resolve: {
    alias: {
      'react': 'https://cdn.skypack.dev/react@17',
      'react-dom': 'https://cdn.skypack.dev/react-dom@17'
    }
  },
  plugins: [reactRefresh()]
});

rollupOptions.external and rollupOptions.output.globals are not suitable for this use case, unless you are only building for legacy browsers, targeting cjs in lib output, or bundling for SSR.

Above skypack cdn urls work fine.
But vite complain about no such file or directory when I switch to a private cdn:

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

// https://vitejs.dev/config/
export default defineConfig({
  resolve: {
    alias: {
      'react': 'https://lf-eden-npm-cdn.bcystatic.com/obj/eden-npm-cdn/v1/dev/react/17.0.2/37d9c5c2.js',
      'react-dom': 'https://lf-eden-npm-cdn.bcystatic.com/obj/eden-npm-cdn/v1/dev/react-dom/17.0.2/93d15a88.js'
    }
  },
  plugins: [
    react()
  ],
})
yarn run v1.22.17
$ vite
node:fs:585
  handleErrorFromBinding(ctx);
  ^

Error: ENOENT: no such file or directory, open 'https://lf-eden-npm-cdn.bcystatic.com/obj/eden-npm-cdn/v1/dev/react/17.0.2/37d9c5c2.js'
    at Object.openSync (node:fs:585:3)
    at Object.readFileSync (node:fs:453:35)
    at extractExportsData (file:///Users/workspace/demo/node_modules/vite/dist/node/chunks/dep-51c4f80a.js:41782:31) {
  errno: -2,
  syscall: 'open',
  code: 'ENOENT',
  path: 'https://lf-eden-npm-cdn.bcystatic.com/obj/eden-npm-cdn/v1/dev/react/17.0.2/37d9c5c2.js'
}

I suffixed the cdn urls with ?t=1 making url not end with .js, it worked.
Maybe vite should read file base on the protocol, not suffix/extname.

from vite-plugin-react.

no13bus avatar no13bus commented on June 12, 2024

I also come across this issue.

System info:
node 18
vite 4.0.0
pnpm 7.20.0

vite.config.ts:

import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import { visualizer } from "rollup-plugin-visualizer";
import path from "path";
import viteCompression from "vite-plugin-compression";
// https://vitejs.dev/config/
export default defineConfig({
  plugins: [
    react(),
    viteCompression(),

    visualizer({
      gzipSize: true,
      brotliSize: true,
      emitFile: false,
      filename: "test.html", //分析图生成的文件名
      open: true, //如果存在本地服务端口,将在打包后自动展示
    }),
  ],
  build: {
    emptyOutDir: false,
    target: ["es2019", "edge88", "firefox78", "chrome58", "safari13.1"],
    cssCodeSplit: true,
    rollupOptions: {
      // 确保外部化处理那些你不想打包进库的依赖
      external: ["react", "react-dom"],
      output: {
        globals: {
          react: "React",
          "react-dom": "ReactDom",
        },
      },
    },
  },

  resolve: {
    alias: {
      "@": path.resolve(__dirname, "src"),
    },
  },

  server: {
    proxy: {
      "/api": {
        target: "http://127.0.0.1:8000",
        changeOrigin: true,
      },
    },
  },
});

index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <link rel="icon" type="image/svg+xml" href="/logo.png" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />

    <script
      crossorigin
      src="https://unpkg.com/[email protected]/umd/react.production.min.js"
    ></script>
    <script
      crossorigin
      src="https://unpkg.com/[email protected]/umd/react-dom.production.min.js"
    ></script>

    <link
      rel="stylesheet"
      href="https://gw.alipayobjects.com/os/k/font/lxgwwenkaiscreenr.css"
      rel="preload"
      as="font"
    />
    <title>web</title>
  </head>
  <body>
    <div id="root"></div>
    <script type="module" src="/src/main.tsx"></script>
  </body>
</html>

the error is Uncaught TypeError: Failed to resolve module specifier "react". Relative references must start with either "/", "./", or "../".
How to fix this bug?

from vite-plugin-react.

github-actions avatar github-actions commented on June 12, 2024

Hello @lichenbuliren. 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.

from vite-plugin-react.

no13bus avatar no13bus commented on June 12, 2024

This is my demo which has the issue

Uncaught TypeError: Failed to resolve module specifier "react". Relative references must start with either "/", "./", or "../".

https://codesandbox.io/p/sandbox/billowing-haze-z48xi5?file=%2Fvite.config.ts&selection=%5B%7B%22endColumn%22%3A11%2C%22endLineNumber%22%3A7%2C%22startColumn%22%3A11%2C%22startLineNumber%22%3A7%7D%5D

@ArnaudBarre

from vite-plugin-react.

Related Issues (20)

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.