Giter VIP home page Giter VIP logo

esbuild-envfile-plugin's People

Contributors

overdrivemachines avatar pdavid0 avatar renanpvaz avatar rsdsllc-com-dipenc avatar rw3iss avatar ymc9 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar

esbuild-envfile-plugin's Issues

Handle missing .env files or missing ENV variables more gracefully

Currently, if the .env file is missing in the application directory and on the server, this plugin causes the following error:

Error: R] [plugin env] Maximum call stack size exceeded

    node_modules/esbuild-envfile-plugin/index.js:9:20:
      9 │             if (!fs.existsSync(dir))

The easiest way to reproduce it is to run it in some CI platform, like Github Actions, in a project where the .env file is in .gitignore for obvious reasons.

If, in turn, there is an .env file but it lacks the definition of the required variable, e.g. SENTRY_DSN, then another error is thrown when we want to import such a variable.

ERROR] No matching export in "env-ns:/path_to/.env" for import "SENTRY_DSN"
path_to ... js
1 | import { SENTRY_DSN } from "env";

Of course, this error is a common JS error when importing something that is not exported. In this case, it is probably worth giving an example in the documentation or README how to solve such situations. In the case of SENTRY_DSN this is not a critical variable for the application to work and it is perfectly OK to default to empty string "".

[ERROR] [plugin env] "path" must be a string

If this plugin is used in production mode and there is no .env file, then the following error will be thrown:

[ERROR] [plugin env] "path" must be a string

This happens because esbuild always expects a string for path.
https://github.com/rw3iss/esbuild-envfile-plugin/blob/master/index.js#L10

Fix:

    build.onResolve({ filter: /^env$/ }, (args) => ({
      path: args.path,
      namespace: "env-ns",
      pluginData: { currentDir: args.resolveDir },
    }))

    build.onLoad({ filter: /.*/, namespace: "env-ns" }, async (args) => {
      // try to find the env file
      let envPath = _findEnvFile(args.pluginData.currentDir)
      let contents = JSON.stringify(process.env)

      // if env file exists then add it to contents
      if (envPath) {
        let data = await fs.promises.readFile(envPath, "utf8")
        const buf = Buffer.from(data)
        const config = require("dotenv").parse(buf)
        contents = JSON.stringify({ ...process.env, ...config })
      }

      return {
        contents,
        loader: "json",
      }
    })

Empty .env file required for this plugin to work

I am working on a rails app with esbuild. I am getting an error if I don't have an empty .env file even though I set the required environment variable using "export" command in terminal.

Some of the packages in my package.json file:

{
    "dotenv": "^16.4.5",
    "esbuild": "^0.20.2",
    "esbuild-envfile-plugin": "^1.0.5",
    "esbuild-rails": "^1.0.7",
}

Part of my esbuild.config.mjs:

const config = {
  absWorkingDir: path.join(process.cwd(), "app/javascript"),
  bundle: true,
  entryPoints: entryPoints,
  minify: process.env.RAILS_ENV == "production",
  outdir: path.join(process.cwd(), "app/assets/builds"),
  plugins: [rails(), envFilePlugin],
  loader: {
    ".png": "file",
  },
  publicPath: "/assets",
  assetNames: "[name]-[hash].digested",
};

My javascript has something like this:

import { WELCOME_MSG } from "env";

In terminal I am setting the environment variable:

export WELCOME_MSG=Hello

When I run my rails app, I get the error:
[ERROR] No matching export in "env-ns:env" for import "WELCOME_MSG"

Now if I add an empty .env file with touch .env, there are no errors. I shouldn't need to have an empty .env file for this to work.

utils.js: fs is not defined

In the most recent release, you moved the function findEnvFile to the file utils.js. In that file you need to declare path and fs before using them like this:

const path = require("path");
const fs = require("fs");
const findEnvFile = (dir, rootPath, env) => {
}

By not declaring them, I am getting the error:

image

Could not resolve "env"

Seems the module name is not being resolved for some reason.
I have .env file present in root.
`
✘ [ERROR] Could not resolve "env"

src/redux/constants.js:1:21:
  1 │ import * as env from 'env';

`
Using node v16.17.1.
Managing dependencies with yarn 3.2.4

`The define key "process.env.ProgramFiles(x86)" contains invalid identifier "ProgramFiles(x86)"`

We're currently seeing the following issue when building on windows based systems. It looks like the non-alphanumeric characters (brackets) in CommonProgramFiles(x86) is causing an error.

Is there anyway of filtering these key/value pairs?

Error: Build failed with 2 errors:
error: The define key "process.env.CommonProgramFiles(x86)" contains invalid identifier "CommonProgramFiles(x86)"
error: The define key "process.env.ProgramFiles(x86)" contains invalid identifier "ProgramFiles(x86)"
    at failureErrorWithLog (C:\project\git\project-repo\node_modules\esbuild\lib\main.js:1603:15)
    at C:\project\git\project-repo\node_modules\esbuild\lib\main.js:1249:28 {
  errors: [
    {
      detail: undefined,
      location: null,
      notes: [],
      pluginName: '',
      text: 'The define key "process.env.CommonProgramFiles(x86)" contains invalid identifier "CommonProgramFiles(x86)"'
    },
    {
      detail: undefined,
      location: null,
      notes: [],
      pluginName: '',
      text: 'The define key "process.env.ProgramFiles(x86)" contains invalid identifier "ProgramFiles(x86)"'
    }
  ],
  warnings: []
}
error Command failed with exit code 1.
lerna ERR! yarn run build exited 1 in '@luco/infra'

Error: Cannot find module 'env'

Hi,
I am having issue when using the envfile plugin.

All works fine, esbuild is also successful, post-build env variables are also working.
Now issue arises when we try to start the nodejs server locally.

nodemon local.ts

import * as env from "env";

image

Error: Cannot find module 'env'
Require stack:

  • D:\physioSurge\physioSurge_backend\controllers\authenticationController.ts
  • D:\physioSurge\physioSurge_backend\routes\authentication-routes.ts
  • D:\physioSurge\physioSurge_backend\server.ts
  • D:\physioSurge\physioSurge_backend\local.ts
    at Function.Module._resolveFilename (node:internal/modules/cjs/loader:933:15)
    at Function.Module._resolveFilename.sharedData.moduleResolveFilenameHook.installedValue [as _resolveFilename] (C:\Users\Administrator\AppData\Roaming\npm\node_modules\ts-node\node_modules@cspotcode\source-map-support\source-map-support.js:811:30)
    at Function.Module._load (node:internal/modules/cjs/loader:778:27)
    at Module.require (node:internal/modules/cjs/loader:1005:19)
    at require (node:internal/modules/cjs/helpers:102:18)
    at Object. (D:\physioSurge\physioSurge_backend\controllers\authenticationController.ts:15:1)
    at Module._compile (node:internal/modules/cjs/loader:1105:14)
    at Module.m._compile (C:\Users\Administrator\AppData\Roaming\npm\node_modules\ts-node\src\index.ts:1597:23)
    at Module._extensions..js (node:internal/modules/cjs/loader:1159:10)
    at Object.require.extensions. [as .ts] (C:\Users\Administrator\AppData\Roaming\npm\node_modules\ts-node\src\index.ts:1600:12) {
    code: 'MODULE_NOT_FOUND',
    requireStack: [
    'D:\physioSurge\physioSurge_backend\controllers\authenticationController.ts',
    'D:\physioSurge\physioSurge_backend\routes\authentication-routes.ts',
    'D:\physioSurge\physioSurge_backend\server.ts',
    'D:\physioSurge\physioSurge_backend\local.ts'
    ]
    }

This is my tsconfig.json file

{
"compilerOptions": {
"allowSyntheticDefaultImports": true,
"baseUrl": "./",
"sourceMap": true,
"emitDecoratorMetadata": true,
"esModuleInterop": true,
"experimentalDecorators": true,
"forceConsistentCasingInFileNames": true,
"importHelpers": true,
"lib": ["ES2020"],
"module": "CommonJS",
"resolveJsonModule": true,
"moduleResolution": "node",
"noImplicitAny": false,
"outDir": "dist",
"removeComments": true,
"skipLibCheck": true,
"strict": false,
"strictNullChecks": false,
"target": "ES2020",
"typeRoots": ["node_modules/@types", "types"],
"types": ["node"],
"paths": {
"env": ["types/environment.d.ts"] // this mapping is relative to "baseUrl"
}
},
"include": ["/*.ts", "/.d.ts"],
"exclude": ["dist/
", "node_modules"],
"defaultSeverity": "warning"
}

Could not resolve "env" in production when actual ENV variables are used and .env is missing

Code that depends on the setting of environment variables causes an error when the .env file is missing and the environment variables are set via SHELL. This is usually the case in a production environment. The development environment uses an .env file which is ignored by git. Missing the .env file causes the following error:

Could not resolve "env"

    app/javascript/application.js:
       │ import { SENTRY_DSN } from "env";
       ╵                            ~~~~~

  You can mark the path "env" as external to exclude it from the bundle, which will remove this
  error.

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.