【问题标题】:how to include webpack in in-browser Babel?如何在浏览器 Babel 中包含 webpack?
【发布时间】:2017-04-17 05:11:32
【问题描述】:

我是 React.js 的新手。出于学习目的,我创建了登录页面,您可以找到here

在我的本地项目中,我也将 CDN 用于 babel 和 react,如下所示。

    <script src="https://unpkg.com/react@latest/dist/react.js"></script>
    <script src="https://unpkg.com/react-dom@latest/dist/react-dom.js"></script>
    <script src="https://unpkg.com/babel-standalone@6.15.0/babel.min.js"></script>

我想在这个例子中使用one of the form validation plugin。但是当我试图包括这个(根据文档)

import ValidateableForm from 'react-form-validate';

我收到以下错误。

Uncaught ReferenceError: require is not defined

我浏览了几篇帖子,他们说我必须使用 webpack 或 Rollup 或 Browsify 。我不确定如何将其包含到我当前的本地项目设置中。由于我没有使用 npm(在学习中我不想使用 npm)

  1. 我不知道如何将该插件包含到我的项目中
  2. 如果它已经带有外部站点,我无法计算 找出问题所在。

请帮我解决问题。

【问题讨论】:

  • requireimporttranspiler 解析,转译后的 js 将其捆绑到呈现给浏览器的最终 js 中。这些包含在ES6 中,尚未在浏览器中实现。因此,如果您需要使用特定的 npm 模块,您可以克隆并编译它,并将编译后的 js 使用到您的代码中,或者如果库提供了一个,您可以使用它们。
  • @Panther 重点是在浏览器中运行转译,这样一个人就可以在没有开销的情况下学习

标签: reactjs webpack babeljs rollup


【解决方案1】:

这是一个老问题,但至少目前,使用传统的脚本标签完全可以做到这一点。 This article is very helpful for understanding development setup alternatives for React

在那篇文章中详细介绍了通过脚本标签引入 React、React-Dom 和 Babel 进行开发,就像这样(我链接到 npm 下载的包,但这不是必需的):

<script src="/node_modules/react/umd/react.development.js"></script>
<script src="/node_modules/react-dom/umd/react-dom.development.js"></script>
<script src="/node_modules/@babel/standalone/babel.min.js"></script>

就我而言,我需要引入 react-notification-system 插件:

<script src="/node_modules/react-notification-system/dist/react-notification-system.min.js"></script>

(注意使用编译后的'dist'版本)

一旦包含在内,我就可以像这样使用它:

class MyComponent extends React.Component {
    constructor(props) {
        super(props);

        this.notificationSystem = new ReactNotificationSystem();
    }

    addNotification = event => {
        event.preventDefault();
        const notification = this.notificationSystem.current;
        notification.addNotification({
            message: 'Notification message',
            level: 'success'
        });
    };

    render() {
        return (
            <div>
                <button onClick={this.addNotification}>Add notification</button>
                <ReactNotificationSystem ref={this.notificationSystem} />
            </div>
        );
    }
}

我必须查看插件的代码才能知道名称:ReactNotificationSystem 将可用,您发现的大部分插件文档都没有考虑到这种类型的开发设置,但它确实有效。

【讨论】:

  • 那篇文章太棒了!非常感谢您提供的链接和您的摘要!
猜你喜欢
  • 1970-01-01
  • 2020-07-01
  • 2018-04-16
  • 2016-09-27
  • 1970-01-01
  • 2016-12-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-30
相关资源
最近更新 更多