我具有应用结构:
-- dist
- index.html
-- js
- index.js
- package.json
- package-lock.json
- gulpfile.js
在index.html中,我有这个:
<!DOCTYPE html>
<html>
<head>
<title>Title</title>
<link rel="stylesheet" type="text/css" href="/css/main.css">
</head>
<body>
<div id='root'></div>
<script type="text/javascript" src="/js/index.js"></script>
</body>
</html>
在index.js中,我有一个简单的React应用程序:
import React from 'react';
import ReactDOM from 'react-dom';
ReactDOM.render((
<h1>Hello world</h1>),document.getElementById('root')
);
此脚本在Gulp中具有适当的导入和包:
gulp.task('js',() =>
gulp.src('js/*.js')
.pipe(babel({
presets: ['env','react','es2015']
}))
.pipe(gulp.dest('dist/js'))
);
gulp.task('webserver',function() {
gulp.src('dist')
.pipe(webserver({
livereload: true,directoryListing: true,open: 'http://localhost:8000/index.html'
}));
});
gulp.task('watch',function() {
gulp.watch('styles/**/*.less',['less']);
gulp.watch('js/**/*.js',['js']);
gulp.src('dist')
.pipe(webserver({
open: 'http://localhost:8000/index.html'
}));
});
// + less
gulp.task('default',[ 'less','watch','js']);
它会正确创建js文件的副本并将其添加到dist / js文件夹中,然后服务器开始运行。控制台中的第一个加载抛出错误未能加载资源:服务器以状态404(未找到)index.js:1进行了响应,但是在第二次加载时,它工作正常,但抛出了错误Uncaught ReferenceError:require未定义index:3。
我在互联网上发现了类似的案例,建议是使用browserify或webpack。我尝试使用此脚本来捆绑所有内容,而不是上面的代码:
gulp.task('js',function () {
var b = browserify({
entry: './js/*.js',debug: true,transform: [babelify.configure({
presets: ['env','es2015']
})]
});
return b.bundle()
.pipe(source('index.js'))
.pipe(buffer())
.pipe(sourcemaps.init({loadMaps: true}))
// Add transformation tasks to the pipeline here.
.pipe(uglify())
.on('error',log.error)
.pipe(sourcemaps.write('./'))
.pipe(gulp.dest('./dist/js/'));
});
应用程序已加载,但React不存在。它会相应地创建index.js和index.map,但不会从React中更新DOM。
这是第一次使用Gulp,所以我不确定自己做错了什么。