Skip to content

Vite 5.4.0 env var fails when bundling Vite-bundled libraryΒ #17874

Closed
@bluwy

Description

Describe the bug

This was brought up at #17648 (comment)

When a library uses Vite (library mode) to bundle and uses env var, the const __vite_import_meta_env__ = { may get included in the code. When that happens and we bundle that library in our app, we re-inject the variable declaration again here, which causes a runtime error:

// If there's bare `import.meta.env` references, prepend the banner
if (bareImportMetaEnvRe.test(result.code)) {
result.code = banner + result.code
if (result.map) {
const map = JSON.parse(result.map)
map.mappings = ';' + map.mappings
result.map = map
}
}

Reproduction

silverwind/vite-import-meta#1

Steps to reproduce

No response

System Info

n/a

Used Package Manager

npm

Logs

Click to expand
error during build:
[commonjs--resolver] node_modules/lib/dist/index.js (3392:6): Identifier "__vite_import_meta_env__" has already been declared
file: node_modules/lib/dist/index.js:3392:6

3390: const create = (createState) => createState ? createImpl(createState) : createImpl;
3391: const __vite_import_meta_env__ = { "BASE_URL": "/", "DEV": false, "MODE": "production", "PROD": true, "SSR": false };
3392: function createJSONStorage(getStorage, options2) {
            ^
3393:   let storage;
3394:   try {

    at getRollupError (node_modules/vite/node_modules/rollup/dist/es/shared/parseAst.js:392:41)
    at error (node_modules/vite/node_modules/rollup/dist/es/shared/parseAst.js:388:42)
    at Module.error (node_modules/vite/node_modules/rollup/dist/es/shared/node-entry.js:13944:16)
    at ModuleScope.addDeclaration (node_modules/vite/node_modules/rollup/dist/es/shared/node-entry.js:7362:21)
    at ModuleScope.addDeclaration (node_modules/vite/node_modules/rollup/dist/es/shared/node-entry.js:12075:22)
    at Identifier.declare (node_modules/vite/node_modules/rollup/dist/es/shared/node-entry.js:6960:39)
    at VariableDeclarator.declareDeclarator (node_modules/vite/node_modules/rollup/dist/es/shared/node-entry.js:10661:17)
    at VariableDeclaration.initialise (node_modules/vite/node_modules/rollup/dist/es/shared/node-entry.js:12343:24)
    at convertNode (node_modules/vite/node_modules/rollup/dist/es/shared/node-entry.js:13167:10)
    at convertNodeList (node_modules/vite/node_modules/rollup/dist/es/shared/node-entry.js:13177:34)

Validations

Metadata

Assignees

No one assigned

    Labels

    p4-importantViolate documented behavior or significantly improves performance (priority)regressionThe issue only appears after a new release

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions