vitejs / vite

Next generation frontend tooling. It's fast!
http://vitejs.dev
MIT License
67.09k stars 6.03k forks source link

Build error when using json objects in `define` #10848

Closed lsdsjy closed 10 months ago

lsdsjy commented 1 year ago

Describe the bug

I wrote a logical expression to call a function when some pre-defined constant is truthy:

// main.js
__CONST_OBJ__.SOME_FLAG && doSomething()
// vite.config.js
export default {
  define: {
    __CONST_OBJ__: {
      SOME_FLAG: false,  // the value may be derived from environment variables
    },
  },
};

And running vite build throws error: error during build: Error: Unexpected token.

I think it's because when JS parsers encounter a { at the beginning of a line, it will be treated as the beginning of new block, not an object. See this repl. So the temporary workaround is to make { not the first character of a line, e.g. wrap it inside parenthses(Boolean(__CONST_OBJ__.SOME_FLAG)).

If I understand correctly, a possible fix is to wrap the object expression in parentheses before replacing. Don't know if there are any other pitfalls.

Reproduction

https://stackblitz.com/edit/vitejs-vite-76jfpr?file=main.js,vite.config.js&terminal=dev

Steps to reproduce

Run npm install and yarn build

System Info

System:
    StackBlitz
  npmPackages:
    vite: ^3.2.3 => 3.2.3

Used Package Manager

npm

Logs

No response

Validations

luo3house commented 1 year ago

Vite docs says config define is only a replacement, so you should define the whole expression to replace instead.

// vite.config.js
export default {
  define: {
    '__CONST_OBJ__.SOME_FLAG': false,
  }
}
lsdsjy commented 1 year ago

Vite docs says config define is only a replacement, so you should define the whole expression to replace instead.

According to the docs, the replacement expression can be JSON object. I don't think it's an invalid use case.

sapphi-red commented 10 months ago

This is fixed by #11151 in 5.0.0-beta.13.