我正在尝试将 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/