javascript - 无法在客户端上使用来自 NPM 的 React,因为未定义 'development'。该包是从 Webpack 生成的

标签 javascript node.js npm reactjs webpack

我正在创建一个 React Node.js 应用程序,我正在尝试生成一个 Webpack 包,其中包含我从 NPM 加载的 React 源代码。

不过,客户端好像不能直接使用NPM的React代码。它会触发此错误:

Uncaught ReferenceError: development is not defined

触发异常的代码来自React代码:

sample

有什么我可以做的吗?

编辑

这是我的webpack.config.js:

import _ from 'lodash';
import webpack from 'webpack';
import yargs from 'yargs';
import ExtractTextPlugin from 'extract-text-webpack-plugin';

export default {
    entry: {
        bundle: './src/client.js'
    },

    output: {
        filename: '[name].js',
        path: './dist/assets',
        publicPath: '/assets/'
    },

    externals: undefined,

    resolve: {
        extensions: ['', '.js', '.json']
    },

    module: {
        loaders: [
            {test: /\.js/, loader: 'babel?optional=es7.objectRestSpread!client', exclude: /node_modules/ },
            {test: /\.css/, loader: ExtractTextPlugin.extract("style-loader", "css-loader")},
            {test: /\.less$/, loader:  ExtractTextPlugin.extract("style-loader", "css-loader!less-loader")},
            {test: /\.json$/, loader: 'json'},
            {test: /\.jpe?g$|\.gif$|\.png$/, loader: 'file?name=[name].[ext]'},
            {test: /\.eot$|\.ttf$|\.svg$|\.woff2?$/, loader: 'file?name=[name].[ext]'}
        ]
    },

    plugins: [
        new webpack.DefinePlugin({
            'process.env': {
                'NODE_ENV': 'development'
            },
            'development': true
        }),
        new ExtractTextPlugin('[name].css')
    ]
};

我的 client.js 文件只包含这一行(为了调试这个问题):

import React from 'react';

And here is the resulting bundle

最佳答案

作为字符串传递给 webpack.DefinePlugin 的任何值都被视为代码片段——也就是说,使用

new webpack.DefinePlugin({
  ENV: "development"
});

代码

console.log(ENV);

结果

console.log(development);

相反,你想要

new webpack.DefinePlugin({
  ENV: "\"development\""
});

这将导致

console.log("development");

要解决您的问题,请将您的插件更改为

plugins: [
    new webpack.DefinePlugin({
        'process.env': {
            'NODE_ENV': "'development'"
        }
    }),
    new ExtractTextPlugin('[name].css')
]

我通常允许 webpack 从 process.env.NODE_ENV 读取,这样当您使用 NODE_ENV=production 运行 webpack 时,React 会正确缩小:

new webpack.DefinePlugin({
  "process.env": { NODE_ENV: JSON.stringify(process.env.NODE_ENV || "development") }
})

关于javascript - 无法在客户端上使用来自 NPM 的 React,因为未定义 'development'。该包是从 Webpack 生成的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30835213/

相关文章:

javascript - vuejs 对数组元素使用计算属性

javascript - 递归调用一个ajax函数,直到第一个ajax函数完成

javascript - 为什么模板版本 1+ 从 HTML 按钮中删除类型属性?

node.js - 如何在 Electron 中实现 Google Text to Speech?

npm - 需要帮助理解 `npm audit` 输出中的哈希值

javascript - 如何通过JavaScript获取iFrame信息(引用URL)?

javascript - 我的 Excel 文件中没有显示日期,该文件是使用 Exceljs 在 Nodejs 上创建的

security - NPM 安装是否在沙箱中运行?

javascript - Uncaught Error : connect ETIMEDOUT (net. 套接字)

node.js - 将 async 与异步函数结合使用