我在 Cordova 中实现了一种自定义的“热重载”方式。我不知道它有多原创,但它很适合我的需要。
大致来说,它的工作原理如下:在开发模式下,启动一个静态 Web 服务器,并指示 cordova 内容是该服务器的 url:<content src="http://10.0.3.2:8080" />
.
静态服务器还监听资产(js/css/html)的变化并自动重新加载。我们使用 gulp 连接(https://www.npmjs.com/package/gulp-connect https://www.npmjs.com/package/gulp-connect) 为了达成这个。
在生产模式下,您必须编译资产并指示 cordova 使用常规静态文件来加载您的应用程序。
Details:
In 科尔多瓦.xml这是告诉 cordova 从哪里启动应用程序的行:
<content src="index.html" />
因此,必须将其替换为允许热重载的“动态”版本。我通过使用实现了这一点gulp-connect
它启动一个静态文件服务器。
gulp.task('connect', function () {
return connect.server({
root: 'www',
livereload: true,
fallback: 'www/index.html',
https: false
});
});
我创建了两个任务,用于在开发和生产中切换 cordova 配置:
// Development
// adds the localhost(on the emulator as 10.0.3.2) as
// the content source for the cordova app
gulp.task('cordova-dev-server-android', function () {
return gulp.src(['config.xml'])
.pipe(replace(/(<content src=\")(.+)(\" \/>)/g, "$1http://10.0.3.2:8080$3"))
.pipe(gulp.dest('.'));
});
// Production
// adds the static file as
// the content source for the cordova app
gulp.task('cordova-static-file', function () {
return gulp.src(['config.xml'])
.pipe(replace(/(<content src=\")(.+)(\" \/>)/g, "$1index.html$3"))
.pipe(gulp.dest('.'));
});
一件重要的事情是您必须确保开发 Web 服务器可以访问 Cordova javascript 文件。我再次通过两项开发/生产任务实现了这一目标。
// Development
// Creates symlinks for the devserver
// so the app has access to cordova files
gulp.task('create-cordova-symlink-android', ['remove-cordova-symlink'], function () {
return gulp.src('')
.pipe(exec('ln -sv ../platforms/android/assets/www/cordova.js www'))
.pipe(exec.reporter())
.pipe(exec('ln -sv ../platforms/android/assets/www/cordova_plugins.js www'))
.pipe(exec.reporter())
.pipe(exec('ln -sv ../platforms/android/assets/www/plugins www'))
.pipe(exec.reporter());
});
// Production
// Removes symlinks for production
// see create-cordova-symlink-android
gulp.task('remove-cordova-symlink', function () {
var options = {
continueOnError: true
};
return gulp.src('')
.pipe(exec('rm www/cordova.js', options))
.pipe(exec('rm www/cordova_plugins.js', options))
.pipe(exec('rm -Rf www/plugins', options));
});
我在这里使用 gulp,但这可以使用任何任务运行程序来实现,当然对于其他平台,您必须稍微修改此代码。
希望这可以帮助。