reactjs - 使用 gulp-react 进行非法进口申报

标签 reactjs ecmascript-6 gulp babeljs

我正在尝试将 React 和 ES6 引入到我的应用程序中,该应用程序是用 Gulp 构建的。我可以让 React 单独工作,也可以让 ES6 单独工作。但尝试导入会导致我的 Gulp 构建崩溃。 Gulp 的错误是:

Line 14: Illegal import declaration

我的 HTML 页面包含 React 和构建的 JS 文件:

    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.12.2/react.min.js"></script>
    <script src="js/app.js"></script>

app.js 看起来像这样:

import {Child} from './child.js';

var Parent = React.createClass({
  render: function(){
    const y = 3;  //es6 works
    return (
      <div>
        <div> This is the parent {y}. </div>
        <Child name="child"/>
      </div>
    )
  }
});

React.render(<Parent />, document.getElementById('container'));

child.js 位于同一目录中,如下所示:

var Child = React.createClass({
  render: function(){
    return (
      <div>
        and this is the <b>{this.props.name}</b>.
      </div>
    )
  }
});

export default Child;

我的 Gulp 文件中使用 Babel 编译 ES6 的部分:

gulp.task('babel', function(){
  gulp.src('js/app.js')
    .pipe(react())
    .pipe(babel({
      presets: ['es2015']
    }))
    .pipe(gulp.dest('dist/js'));
});

我遗漏/做错了什么导致我无法使用import

最佳答案

您必须申请 es6module选项 gulp-react允许导入模块:

.pipe(react({
  es6module: true
}))

然后,修复您的导入语句。自 Child默认导出,导入如下:

import Child from './child.js';
<小时/>

注:gulp-react已弃用,取而代之的是 gulp-babel因此,如果您已经将其用于 es2015,我建议您使用它。 。使用gulp-babel相反并安装 react Babel 预设:

npm install --save-dev babel-preset-react

最后,应用到 gulp-babel :

presets: ['es2015', 'react']

关于reactjs - 使用 gulp-react 进行非法进口申报,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44619385/

相关文章:

javascript - 为什么 Bootstrap 4 在 es6 类中使用私有(private)方法?

javascript - JavaScript 中的 "=>"(由等于和大于组成的箭头)是什么意思?

javascript - gulp中解析多个文件生成一个文件

reactjs - 无法有条件地更新 `setState`里面的 `useEffect`

javascript - ReactJS:用于 css 转换的切换类

javascript - 是的,数组验证 - 仅当数组长度大于 1 时才需要值

javascript - 在 javascript 中使用特定键反转对象数组时出现问题(React)

node.js - Visual Studio Code 无法识别 ES6 语法

css - gulp-sass 不导入 scss 文件

html - gulp-changed 有不同的行为