Webpack: Bundle.js - Uncaught ReferenceError: process is not defined

后端 未结 5 1818
轻奢々
轻奢々 2020-12-31 00:06

Here\'s my webpack.config.js

\"use strict\";

module.exports = {
    entry: [\'./main.js\'],
    output: { path: __dirname, filename: \'bund         


        
5条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-31 00:20

    With dotenv node module:

    STEP 1: INSTALL dotenv:

    yarn add -D dotenv or npm i -D dotenv

    STEP 2: ADD .env file in your project root with the required variables:

    NODE_ENV=development
    apiKey=w23io222929kdjfk
    domain=example.domain.org
    

    STEP 3: DEFINE these variables with webpack.DefinePlugin:

    // webpack.config.js
    const webpack = require('webpack')
    const dotenv = require('dotenv')
    
    module.exports = {
      //...
      plugins: [
        // ...
        new webpack.DefinePlugin({
           'process.env': JSON.stringify(dotenv.config().parsed) // it will automatically pick up key values from .env file
        })
        // ...
      ]
      //...
    }
    

    STEP 4: ACCESS environment variables in your source code:

    // src/index.js
    alert(process.env.NODE_ENV)
    alert(process.env.apiKey)
    


    Important Links:

    • dotenv: https://www.npmjs.com/package/dotenv
    • webpack.DefinePlugin: https://webpack.js.org/plugins/define-plugin/

    Good Luck...

提交回复
热议问题