mrsteele / dotenv-webpack

A secure webpack plugin that supports dotenv and other environment variables and only exposes what you choose and use.
MIT License
1.3k stars 76 forks source link

'process' is not defined #264

Closed logicappsource closed 4 years ago

logicappsource commented 4 years ago

HI I am wrapping my head before going to production..

I created .env inside src/ folder. install with npm.

Line 120:61: 'process' is not defined

I get no matter if I print console.log(process.env.NODE_ENV)

mrsteele commented 4 years ago

What version do you have? I would update to the latest as there was a bug that existed a week or so ago that caused that.

logicappsource commented 4 years ago

Thank you the response sir. This is my .json file

{ "name": "mynordicroombusiness", "version": "0.1.0", "private": true, "dependencies": { "@babel/core": "7.4.3", "@babel/runtime": "^7.9.6", "@material-ui/core": "^4.11.0", "@material-ui/icons": "^4.9.1", "@material-ui/lab": "^4.0.0-alpha.51", "@svgr/webpack": "4.1.0", "@typescript-eslint/eslint-plugin": "1.6.0", "@typescript-eslint/parser": "1.6.0", "@woocommerce/woocommerce-rest-api": "^1.0.1", "axios": "^0.18.1", "babel-eslint": "10.0.1", "babel-jest": "24.7.1", "babel-loader": "8.0.5", "babel-plugin-named-asset-import": "^0.3.6", "babel-preset-react-app": "^8.0.0", "case-sensitive-paths-webpack-plugin": "2.2.0", "css-loader": "2.1.1", "deck.gl": "^7.3.15", "dotenv": "^6.2.0", "dotenv-expand": "4.2.0", "eslint-config-react-app": "^4.0.1", "eslint-loader": "2.1.2", "eslint-plugin-flowtype": "2.50.1", "eslint-plugin-import": "2.16.0", "eslint-plugin-jsx-a11y": "6.2.1", "eslint-plugin-react-hooks": "^1.7.0", "file-loader": "3.0.1", "fs-extra": "7.0.1", "html-webpack-plugin": "4.0.0-beta.5", "identity-obj-proxy": "3.0.0", "is-wsl": "^1.1.0", "jest": "24.7.1", "jest-environment-jsdom-fourteen": "0.1.0", "jest-resolve": "24.7.1", "jest-watch-typeahead": "0.3.0", "lazysizes": "^5.2.0", "mini-css-extract-plugin": "0.5.0", "optimize-css-assets-webpack-plugin": "5.0.1", "pnp-webpack-plugin": "1.2.1", "postcss-flexbugs-fixes": "4.1.0", "postcss-loader": "3.0.0", "postcss-normalize": "7.0.1", "postcss-preset-env": "6.6.0", "postcss-safe-parser": "4.0.1", "react": "^16.8.0", "react-app-polyfill": "^1.0.6", "react-autosuggest": "^9.4.3", "react-country-flag": "^1.1.0", "react-debounce-input": "^3.2.2", "react-dev-utils": "^9.1.0", "react-dom": "^16.13.1", "react-infinite-scroller": "^1.2.4", "react-instantsearch-dom": "^5.7.0", "react-instantsearch-dom-maps": "^5.7.0", "react-map-gl": "^4.1.16", "react-map-gl-geocoder": "^2.0.11", "react-multi-select-component": "^3.0.2", "react-redux": "^7.2.0", "react-router-dom": "^5.1.2", "react-scrolltop-button": "^0.1.6", "react-swipeable-views": "^0.13.9", "redux": "^4.0.5", "redux-thunk": "^2.3.0", "resolve": "1.10.0", "sass-loader": "7.1.0", "semver": "^6.3.0", "style-loader": "0.23.1", "styled-components": "^5.1.1", "terser-webpack-plugin": "1.2.3", "url-loader": "1.1.2", "webpack": "4.29.6", "webpack-dev-server": "3.2.1", "webpack-manifest-plugin": "2.0.4", "workbox-webpack-plugin": "4.2.0" }, "scripts": { "start": "node scripts/start.js", "build": "node scripts/build.js", "test": "node scripts/test.js" }, "eslintConfig": { "extends": "react-app" }, "browserslist": { "production": [ ">0.2%", "not dead", "not op_mini all" ], "development": [ "last 1 chrome version", "last 1 firefox version", "last 1 safari version" ] }, "jest": { "collectCoverageFrom": [ "src//*.{js,jsx,ts,tsx}", "!src/*/.d.ts" ], "setupFiles": [ "react-app-polyfill/jsdom" ], "setupFilesAfterEnv": [], "testMatch": [ "/src//tests/*/.{js,jsx,ts,tsx}", "/src/*/.{spec,test}.{js,jsx,ts,tsx}" ], "testEnvironment": "jest-environment-jsdom-fourteen", "transform": { "^.+\.(js|jsx|ts|tsx)$": "/node_modules/babel-jest", "^.+\.css$": "/config/jest/cssTransform.js", "^(?!.*\.(js|jsx|ts|tsx|css|json)$)": "/config/jest/fileTransform.js" }, "transformIgnorePatterns": [ "[/\\]node_modules[/\\].+\.(js|jsx|ts|tsx)$", "^.+\.module\.(css|sass|scss)$" ], "modulePaths": [], "moduleNameMapper": { "^react-native$": "react-native-web", "^.+\.module\.(css|sass|scss)$": "identity-obj-proxy" }, "moduleFileExtensions": [ "web.js", "js", "web.ts", "ts", "web.tsx", "tsx", "json", "web.jsx", "jsx", "node" ], "watchPlugins": [ "jest-watch-typeahead/filename", "jest-watch-typeahead/testname" ] }, "babel": { "presets": [ "react-app" ] }, "devDependencies": { "dotenv-webpack": "^5.0.0", "eslint": "^7.9.0", "eslint-plugin-react": "^7.20.6" } }

AuthorProxy commented 4 years ago

Same error after updating to webpack 5 and all other latest dev deps, config:

  "devDependencies": {
    "@babel/cli": "^7.12.1",
    "@babel/plugin-proposal-class-properties": "^7.12.1",
    "@babel/plugin-proposal-decorators": "^7.12.1",
    "@babel/plugin-proposal-do-expressions": "^7.12.1",
    "@babel/plugin-proposal-export-default-from": "^7.12.1",
    "@babel/plugin-proposal-export-namespace-from": "^7.12.1",
    "@babel/plugin-proposal-function-bind": "^7.12.1",
    "@babel/plugin-proposal-function-sent": "^7.12.1",
    "@babel/plugin-proposal-json-strings": "^7.12.1",
    "@babel/plugin-proposal-logical-assignment-operators": "^7.12.1",
    "@babel/plugin-proposal-nullish-coalescing-operator": "^7.12.1",
    "@babel/plugin-proposal-numeric-separator": "^7.12.1",
    "@babel/plugin-proposal-optional-chaining": "^7.12.1",
    "@babel/plugin-proposal-pipeline-operator": "^7.12.1",
    "@babel/plugin-proposal-throw-expressions": "^7.12.1",
    "@babel/plugin-syntax-dynamic-import": "^7.8.3",
    "@babel/plugin-syntax-import-meta": "^7.10.4",
    "@babel/plugin-transform-flow-strip-types": "^7.12.1",
    "@babel/preset-flow": "^7.12.1",
    "@babel/preset-react": "^7.12.1",
    "@webpack-cli/migrate": "^1.0.2",
    "babel-eslint": "^10.1.0",
    "babel-jest": "^26.6.1",
    "babel-loader": "^8.1.0",
    "babel-plugin-import": "^1.13.1",
    "babel-plugin-macros": "^2.8.0",
    "babel-plugin-module-resolver": "^4.0.0",
    "babel-plugin-react-intl": "^8.2.10",
    "babel-plugin-styled-components": "^1.11.1",
    "babel-plugin-transform-react-remove-prop-types": "^0.4.24",
    "browserslist": "^4.14.5",
    "bundle-stats-webpack-plugin": "^2.3.0",
    "circular-dependency-plugin": "^5.2.2",
    "clean-webpack-plugin": "^3.0.0",
    "css-loader": "^5.0.0",
    "dotenv-webpack": "^5.0.1",
    "eslint": "^7.12.1",
    "eslint-config-airbnb": "^18.2.0",
    "eslint-import-resolver-babel-module": "^5.2.0",
    "eslint-import-resolver-node": "^0.3.4",
    "eslint-nibble": "^6.0.0",
    "eslint-plugin-babel": "^5.3.1",
    "eslint-plugin-flowtype": "^5.2.0",
    "eslint-plugin-formatjs": "^2.8.0",
    "eslint-plugin-import": "^2.22.1",
    "eslint-plugin-jsx-a11y": "^6.4.1",
    "eslint-plugin-module-resolver": "^1.0.0",
    "eslint-plugin-react": "^7.21.5",
    "eslint-plugin-react-hooks": "^4.2.0",
    "eslint-webpack-plugin": "^2.1.0",
    "fast-async": "^6.3.8",
    "favicons-webpack-plugin": "^4.2.0",
    "flow-bin": "^0.137.0",
    "flow-coverage-report": "^0.8.0",
    "flow-typed": "^3.2.1",
    "friendly-errors-webpack-plugin": "^1.7.0",
    "git-revision-webpack-plugin": "^3.0.6",
    "html-webpack-plugin": "^4.5.0",
    "husky": "^4.3.0",
    "image-trace-loader": "^1.0.2",
    "jest": "^26.6.1",
    "lint-staged": "^10.5.0",
    "node-notifier": "^8.0.0",
    "nodemon": "^2.0.6",
    "npm-check-updates": "^9.2.3",
    "npm-force-resolutions": "0.0.3",
    "npm-run-all": "^4.1.5",
    "prettier": "^2.1.2",
    "standard-version": "^9.0.0",
    "style-loader": "^2.0.0",
    "stylelint": "^13.7.2",
    "stylelint-a11y": "^1.2.3",
    "stylelint-config-airbnb": "0.0.0",
    "stylelint-config-idiomatic-order": "^8.1.0",
    "stylelint-config-prettier": "^8.0.2",
    "stylelint-config-rational-order": "^0.1.2",
    "stylelint-config-recommended": "^3.0.0",
    "stylelint-config-standard": "^20.0.0",
    "stylelint-config-styled-components": "^0.1.1",
    "stylelint-custom-processor-loader": "^0.6.0",
    "stylelint-order": "^4.1.0",
    "stylelint-prettier": "^1.1.2",
    "stylelint-processor-styled-components": "^1.10.0",
    "stylelint-scss": "^3.18.0",
    "svg-react-loader": "^0.4.6",
    "svgo": "^1.3.2",
    "unused-webpack-plugin": "^2.4.0",
    "webpack": "^5.3.2",
    "webpack-bundle-analyzer": "^3.9.0",
    "webpack-cli": "^4.1.0",
    "webpack-dev-server": "^3.11.0",
    "webpack-manifest-plugin": "^2.2.0",
    "webpack-stats-plugin": "^1.0.2",
    "write-file-webpack-plugin": "^4.5.1"
  },
  "dependencies": {
    "@babel/core": "^7.12.3",
    "@babel/preset-env": "^7.12.1",
    "@babel/register": "^7.12.1",
    "@formatjs/intl-relativetimeformat": "^7.3.1",
    "@fortawesome/fontawesome-svg-core": "^1.2.32",
    "@fortawesome/free-brands-svg-icons": "^5.15.1",
    "@fortawesome/free-regular-svg-icons": "^5.15.1",
    "@fortawesome/free-solid-svg-icons": "^5.15.1",
    "@fortawesome/react-fontawesome": "^0.1.12",
    "@hot-loader/react-dom": "^16.11.0",
    "@sentry/browser": "^5.27.2",
    "antd": "^3.26.7",
    "axios": "^0.19.2",
    "bootstrap": "^4.4.1",
    "connect-timeout": "^1.9.0",
    "connected-react-router": "^6.6.1",
    "core-js": "^3.6.5",
    "date-fns": "^2.9.0",
    "date-fns-tz": "^1.0.9",
    "dotenv": "^8.2.0",
    "express": "^4.17.1",
    "final-form": "^4.18.6",
    "final-form-arrays": "^3.0.2",
    "final-form-calculate": "^1.3.1",
    "flat": "^5.0.2",
    "history": "^4.10.1",
    "http-proxy-middleware": "^1.0.6",
    "intl": "^1.2.5",
    "intl-pluralrules": "^1.1.1",
    "jsonwebtoken": "^8.5.1",
    "jwt-decode": "^3.0.0",
    "logrocket": "^1.0.14",
    "morgan": "^1.10.0",
    "morphism": "^1.12.3",
    "normalizr": "^3.6.1",
    "path": "^0.12.7",
    "prop-types": "^15.7.2",
    "qs": "^6.9.4",
    "rc-slider": "^8.7.1",
    "re-reselect": "^3.4.0",
    "react": "^16.12.0",
    "react-countdown": "^2.2.0",
    "react-datepicker": "^2.11.0",
    "react-dom": "^16.12.0",
    "react-final-form": "^6.3.3",
    "react-flip-toolkit": "^7.0.7",
    "react-gtm-module": "^2.0.8",
    "react-helmet": "^5.2.1",
    "react-hot-loader": "4.12.6",
    "react-id-swiper": "^2.4.0",
    "react-intl": "^3.11.0",
    "react-loadable": "^5.5.0",
    "react-modal": "^3.11.1",
    "react-redux": "^7.1.3",
    "react-responsive-modal": "^4.0.1",
    "react-router-dom": "^5.1.2",
    "react-select": "^3.0.8",
    "react-table": "7.0.0-beta.0",
    "react-text-mask": "^5.4.3",
    "react-tooltip": "^3.11.2",
    "react-yandex-maps": "^4.2.0",
    "recompose": "^0.30.0",
    "redux": "^4.0.5",
    "redux-actions": "^2.6.5",
    "redux-auth-wrapper": "^3.0.0",
    "redux-devtools-extension": "^2.13.8",
    "redux-form": "^8.2.6",
    "redux-immutable-state-invariant": "^2.1.0",
    "redux-logger": "^3.0.6",
    "redux-reset": "^0.3.0",
    "redux-thunk": "^2.3.0",
    "reselect": "^4.0.0",
    "response-time": "^2.3.2",
    "shortid": "^2.2.16",
    "styled-components": "^5.0.0",
    "swiper": "^5.3.0",
    "text-mask-addons": "^3.8.0",
    "winston": "^3.3.3"
  },
mrsteele commented 4 years ago

What about webpack config?

AuthorProxy commented 4 years ago
/* eslint-env node */
/* eslint-disable import/first */

require('@babel/register')({
  presets: ['@babel/preset-env']
});

import path from 'path';
import dotenv from 'dotenv';
import webpack from 'webpack';

import DotenvWebpackPlugin from 'dotenv-webpack';

import CircularDependencyPlugin from 'circular-dependency-plugin';
import { CleanWebpackPlugin } from 'clean-webpack-plugin';
import WriteFilePlugin from 'write-file-webpack-plugin';
import HtmlWebPackPlugin from 'html-webpack-plugin';
import FaviconsWebpackPlugin from 'favicons-webpack-plugin';
import FriendlyErrorsWebpackPlugin from 'friendly-errors-webpack-plugin';
import { WindowsBalloon } from 'node-notifier';
import UnusedWebpackPlugin from 'unused-webpack-plugin';

import ManifestPlugin from 'webpack-manifest-plugin';
import { getWebpackDevServerOptions } from './configs';

const PATHS = {
  src: path.resolve(__dirname, 'src'),
  images: path.resolve(__dirname, 'src/assets/images'),
  fonts: path.resolve(__dirname, 'src/assets/fonts'),
  pdfs: path.resolve(__dirname, 'src/assets/pdf')
};

const styleLoader = {
  loader: 'style-loader',
  options: {
    insert: 'head',
    injectType: 'singletonStyleTag'
  }
};

const cssLoader = {
  loader: 'css-loader',
  options: {
    sourceMap: true
  }
};

const moduleCssLoader = {
  loader: 'css-loader',
  options: {
    ...cssLoader.options,
    modules: true,
    importLoaders: 1
  }
};

const config = {
  mode: 'development',
  devtool: 'source-map',
  entry: {
    main: `${PATHS.src}/index.js`,
    icons: `${PATHS.src}/components/iconControls.js`
  },
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: '[name].[contenthash:8].js',
    chunkFilename: '[name].[chunkhash:8].js'
  },
  resolve: {
    mainFields: ['browser', 'main', 'module'],
    alias: {
      'react-dom': '@hot-loader/react-dom'
    }
  },
  module: {
    rules: [{
      test: /\.(js|jsx)$/,
      exclude: /node_modules/,
      use: ['babel-loader', {
        loader: 'stylelint-custom-processor-loader',
        options: {
          emitWarning: true
        }
      }]
    }, {
      test: /\.css$/,
      include: /\.module\.css$/,
      use: [styleLoader, /* moduleExtractCssChunksLoader, */ moduleCssLoader]
    }, {
      test: /\.css$/,
      exclude: /\.module\.css$/,
      use: [styleLoader, /* extractCssChunksLoader, */ cssLoader]
    }, {
      test: /\.(svg|eot|ttf|otf|woff|woff2)$/,
      include: PATHS.fonts,
      type: 'asset/resource',
      generator: {
        filename: 'assets/fonts/[name][ext]'
      }
    }, {
      test: /\.pdf$/,
      include: PATHS.pdfs,
      type: 'asset/resource',
      generator: {
        filename: 'assets/pdf/[name][ext]'
      }
    }, {
      test: /\.(png|gif|jpg|jpeg)$/,
      include: PATHS.images,
      type: 'asset',
      parser: {
        dataUrlCondition: {
          maxSize: 20 * 1024
        }
      },
      generator: {
        filename: 'assets/images/[name][ext]',
      }
    }, {
      test: /\.txt$/,
      type: 'asset/source'
    }, {
      test: /\.svg$/,
      include: PATHS.images,
      use: 'svg-react-loader'
    }]
  },
  optimization: {
    runtimeChunk: {
      name: 'manifest'
    },
    splitChunks: {
      cacheGroups: {
        defaultVendors: {
          test: /[\\/]node_modules[\\/]/,
          name: 'vendors',
          chunks: 'all'
        }
      }
    }
  },
  plugins: [
    new DotenvWebpackPlugin({ systemvars: true }),

    // new webpack.DefinePlugin({
    //   'process.env': JSON.stringify(dotenv.config().parsed)
    // }),

    new CircularDependencyPlugin({
      failOnError: false,
      exclude: /node_modules/,
      cwd: PATHS.src
    }),

    new CleanWebpackPlugin({ cleanStaleWebpackAssets: false }),
    new WriteFilePlugin(),

    new HtmlWebPackPlugin({ template: './src/index.html' }),
    new FaviconsWebpackPlugin({
      logo: './src/assets/images/favicon.png',
      favicons: {
        appShortName: 'hrk',
        icons: {
          android: true,
          appleIcon: true,
          appleStartup: true,
          coast: true,
          favicons: true,
          firefox: true,
          windows: true,
          yandex: true
        }
      }
    }),

    new FriendlyErrorsWebpackPlugin({
      compilationSuccessInfo: {
        messages: ['You application is running here http://localhost:3000'],
        notes: ['Some additionnal notes to be displayed unpon successful compilation']
      },
      onErrors: (severity, errors) => {
        if (severity !== 'error') {
          return;
        }

        const error = errors[0];
        new WindowsBalloon().notify({
          title: 'Webpack compilation error',
          message: `${severity}: ${error.name}`,
          subtitle: error.file || ''
        });
      },

      clearConsole: false
    }),

    new UnusedWebpackPlugin({
      directories: [PATHS.src],
      exclude: [
        '*.spec.js',
        '*.mocks.js',
        'adapters/**/*.js',
        'utils/testUtils.js',
        'assets/images/loaders/**/*.*'
      ]
    }),

    new ManifestPlugin({
      fileName: 'manifest.mappings.js',
      writeToFileEmit: true
    })
  ]
};

module.exports = env => {
  process.env.BABEL_ENV ||= env;
  if (env && env.cli) {
    global.console.log(`Running cli webpack-dev-server: ${JSON.stringify(env || 'not specified')}`);
    config.devServer = getWebpackDevServerOptions();
    config.devtool = 'cheap-source-map';
  }

  const smp = null;
  return smp ? smp.wrap(config) : config;
};

I tried webpack.DefinePlugin it wasn't working, then I update these packages:

"favicons-webpack-plugin": "^5.0.0-alpha.3",
"html-webpack-plugin": "^5.0.0-alpha.10",
"webpack-manifest-plugin": "^3.0.0-rc.0",

and it begins working, but dotenv-webpack plugin still not

mrsteele commented 4 years ago

@logicappsource your issue is you need to make sure you point to that .env file. I believe it will assume webpack config and .env file are in your project root, but feel free to use the path prop to point to your env file.

twgraham commented 4 years ago

Experiencing the same issue after webpack 5/dotenv-webpack-plugin 5 upgrade, however I notice the same issue exists if I try to use the DefinePlugin directly. I think something else is going on here...

mrsteele commented 4 years ago

Would anyone here mind sharing with me the Repo? Webpack 5 has been painfully inconsistent with results for me and I want to make sure I am seeing exactly what you all are seeing.

twgraham commented 4 years ago

@mrsteele sorry, unfortunately I'm unable to share the repo I'm experiencing this on. I'll see if I can produce a repro example though.

I do have to go back on what I said about the DefinePlugin though. When I use it as @AuthorProxy has, it works as expected. e.g.

{
  plugins: [
    new DefinePlugin({
      'process.env': JSON.stringify(dotenv.parsed)
    })
  ]
}
mrsteele commented 4 years ago

Are you destructing your variables? That is a known limitation. We intentionally don't write them that way because you end up leaking all variables on every env statement.

twgraham commented 4 years ago

No destructing of variables, just using them as is e.g. process.env.SOME_ENVIRONMENT_VARIABLE

AuthorProxy commented 4 years ago

Would anyone here mind sharing with me the Repo? Webpack 5 has been painfully inconsistent with results for me and I want to make sure I am seeing exactly what you all are seeing.

I can share repo with you only via teamviewer|anydesk if you interested

demfabris commented 4 years ago

Same issue here. Only works inside console.log()

mrsteele commented 4 years ago

@fabricio7p @AuthorProxy (and really anyone interested).

Would anyone be interested in trying out what I have drafted to fix this?

  1. Download this: https://github.com/mrsteele/dotenv-webpack/archive/feature/fixMissingIssue.zip
  2. npm i && npm run build
  3. Copy the contents of the dist folder and paste it into your project at node_modules/dotenv-webpack/dist (note: this is overriding what you got)
  4. Let me know if that resolved your issue.
demfabris commented 4 years ago

@fabricio7p @AuthorProxy (and really anyone interested).

Would anyone be interested in trying out what I have drafted to fix this?

  1. Download this: https://github.com/mrsteele/dotenv-webpack/archive/feature/fixMissingIssue.zip
  2. npm i && npm run build
  3. Copy the contents of the dist folder and paste it into your project at node_modules/dotenv-webpack/dist (note: this is overriding what you got)
  4. Let me know if that resolved your issue.

This works!

AuthorProxy commented 4 years ago

confirm

mrsteele commented 4 years ago

@fabricio7p last question before I merge, have you tried v3 of this plugin? I think webpack did something and it broke not only my plugin but anyone who used DefinePlugin in that window. Can you let me know if that works for you?

demfabris commented 4 years ago

@fabricio7p last question before I merge, have you tried v3 of this plugin? I think webpack did something and it broke not only my plugin but anyone who used DefinePlugin in that window. Can you let me know if that works for you?

Yep, just confirmed that v3 works too

mrsteele commented 4 years ago

@fabricio7p Thanks so much for verifying! You can see all the chatter here which made me think my changed broke something: https://github.com/mrsteele/dotenv-webpack/issues/240

I'm going to go ahead and merge #267 which means v5.1.0 should have the latest and everything you need, and as part of that close this ticket out. If anyone experiences problems with this though definitely reopen. I'll be staring at twitter which is much better if you need to reach out to me: https://twitter.com/matt_r_steele