为什么webpack在这里没有定义反应?

时间:2019-05-13 07:43:17

标签: javascript webpack

我有一些这样的代码

import React, { Component } from 'react';
import AppRouter from './app/route';
import ReactDOM from 'react-dom';


// Disable react dev tools in production
if (process.env.NODE_ENV === 'production'
    && window.__REACT_DEVTOOLS_GLOBAL_HOOK__
    && Object.keys(window.__REACT_DEVTOOLS_GLOBAL_HOOK__._renderers).length
) window.__REACT_DEVTOOLS_GLOBAL_HOOK__._renderers = {};

// Enable React hot reload in development
if (process.env.NODE_ENV === 'development') {
    module.hot.accept('./app.js', () => {
        ReactDOM.render(<AppRouter />, document.getElementById('complianceApp'));
    });
}

ReactDOM.render(<AppRouter />, document.getElementById('complianceApp'));

与webpack一起构建。我需要在其他几个地方做类似的事情,所以我想我将制定一个通用的解决方案,将大部分代码取出并放入SPA构建器中-如下所示

import React, { Component } from 'react';
import ReactDOM from 'react-dom';

const spa_boilerplate = (component, path, elID) => {
    if (process.env.NODE_ENV === 'production'
    && window.__REACT_DEVTOOLS_GLOBAL_HOOK__
    && Object.keys(window.__REACT_DEVTOOLS_GLOBAL_HOOK__._renderers).length
    ) { window.__REACT_DEVTOOLS_GLOBAL_HOOK__._renderers = {};}

    // Enable React hot reload in development
    if (process.env.NODE_ENV === 'development') {
        module.hot.accept(path, () => {
            ReactDOM.render(component, document.getElementById(elID));
        });
    }

    ReactDOM.render(component, document.getElementById(elId));
}

export default spa_boilerplate;

然后将其导入到app.js中

import AppRouter from './app/route';
import spa_boilerplate from './shared/spa_boilerplate';

spa_boilerplate(<AppRouter />,  '../../app.js', 'complianceApp');

运行此命令时,我会收到错误消息

ReferenceError: React is not defined

app.js line 4147 > eval:16:1
    <anonymous> webpack:///./src/app.js?:16
    js http://localhost:8001/app.js:4147
    __webpack_require__ http://localhost:8001/app.js:724
    fn http://localhost:8001/app.js:101
    <anonymous> webpack:///multi_(webpack)-dev-server/client?:3
    0 http://localhost:8001/app.js:4515
    __webpack_require__ http://localhost:8001/app.js:724
    <anonymous> http://localhost:8001/app.js:791
    <anonymous> http://localhost:8001/app.js:794

如果我查看构建的Webpack,它具有以下内容:

Object(_shared_spa_boilerplate__WEBPACK_IMPORTED_MODULE_1__["default"])(React.createElement(_app_route__WEBPACK_IMPORTED_MODULE_0__["default"], null), '../../app.js', 'complianceApp');

所以我可以看到其中没有定义React-如何定义它?

2 个答案:

答案 0 :(得分:0)

您将React导入到app.js吗?

Sheet

答案 1 :(得分:0)

每当您使用jsx时,就在app.js中使用<Approuter />时,它都将被转换为React.createSomethingOrOther。因此,您必须将React显式导入任何使用jsx的模块中。只是import React from "react";在您的app.js中。