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

旧街凉风 提交于 2020-06-08 07:09:55

问题


Here's my webpack.config.js

"use strict";

module.exports = {
    entry: ['./main.js'],
    output: { path: __dirname, filename: 'bundle.js' },
    module: {
        loaders: [
            {
                test: /.js?$/,
                loader: 'babel-loader',
                exclude: /node_modules/,
                query: {
                    presets: ['es2015', 'react']
                }
            },
            {test: /\.json$/, loader: "json"},
        ]
    },
    externals: {
        React: 'react',
    },
    target: "node",
};

And Main.js

import React from 'react';
import ReactDOM from 'react-dom';
import {Table, Column, Cell} from 'fixed-data-table';
import Chart from 'chartjs';
import jQuery from 'jquery';
import vis from 'vis';
import babel from 'babel-core';

The Bundle.js is inserted in my Index.html. The browser then gives the error:

Uncaught ReferenceError: process is not defined
    at Object.measureMethods (bundle.js:1297)
    at Object.<anonymous> (bundle.js:530)
    at __webpack_require__ (bundle.js:20)
    at Object.<anonymous> (bundle.js:288)
    at __webpack_require__ (bundle.js:20)
    at Object.<anonymous> (bundle.js:158)
    at __webpack_require__ (bundle.js:20)
    at Object.<anonymous> (bundle.js:110)
    at __webpack_require__ (bundle.js:20)
    at Object.<anonymous> (bundle.js:90)

What should I change in the webpack.config.js to make this error go away?


回答1:


You need to add a plugin to define your env (in webpack config):

   plugins: [
        new webpack.DefinePlugin({
            'process.env.NODE_ENV': JSON.stringify('development')
        })
    ],



回答2:


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...



来源:https://stackoverflow.com/questions/41359504/webpack-bundle-js-uncaught-referenceerror-process-is-not-defined

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!