我即将让 grunt-browser-sync
正常工作,但还远未完成。
我想出了这个 Gruntfile:
module.exports = function(grunt) {
grunt.initConfig({
pkg : grunt.file.readJSON('package.json'),
concat : {
dist : {
src : ['js/libs/*.js', 'js/custom/*.js'],
dest : 'js/build/production.js',
}
},
uglify : {
dist : {
src : 'js/build/production.js',
dest : 'js/build/production.min.js'
}
},
sass : {
dist : {
options : {
style : 'compressed',
compass : 'true',
},
files : {
'css/main.css' : 'sass/main.scss'
}
}
},
autoprefixer : {
options : {
browsers : ['> 5%', 'last 2 version', 'ie 8', 'ie 9']
},
dist : {
files : {
'css/main.css' : 'css/main.css'
}
}
},
watch : {
options : {
livereload : true
},
content : {
files : '*.html',
tasks : ['browserSync']
},
scripts : {
files : ['js/libs/*.js', 'js/custom/*.js'],
tasks : ['concat', 'uglify', 'browserSync'],
options : {
spawn : false,
},
},
css : {
files : ['sass/**/*.scss'],
tasks : ['sass', 'autoprefixer', 'browserSync'],
options : {
spawn : false,
}
}
},
browserSync : {
files : {
src : ['css/*.css', 'images/*.*', 'js/build/production.min.js', '*.html'],
},
options : {
server: {
baseDir: "./",
},
watchTask : true
}
}
});
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-browser-sync');
grunt.loadNpmTasks('grunt-contrib-sass');
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-autoprefixer');
grunt.loadNpmTasks('grunt-newer');
grunt.registerTask('newer', ['browserSync', 'sass', 'autoprefixer', 'concat', 'uglify']);
};
我想要的是:
- 在终端上键入
grunt watch
,然后自动在浏览器的静态服务器页面中打开我的index.html
。 - 当 CSS、JS 或图像更改时实时重新加载的页面。
我的配置发生的情况如下:
- 只有在保存文件时才会打开一个新的浏览器窗口
- 每次我保存东西时,都会打开多个浏览器窗口,并且
localhost
数字不断变化,导致插件完全无用
我知道我已经在文件的每个可能位置注册了 tasks : ['browserSync']
,但这是浏览器同步做某事的唯一方式.我希望这就足够了:
grunt.registerTask('newer', ['browserSync', 'sass', 'autoprefixer', 'concat', 'uglify']);
但我没有运气。浏览器同步触发器,但没有打开静态服务器。
最佳答案
此处为 BrowserSync 作者。
问题是您多次启动 BrowserSync 任务 - 这不是正确的使用方法。
查看 http://www.browsersync.io/docs/grunt/ 中的示例- 你应该独立(和之前)启动 BrowserSync 任何其他像这样的监视任务。
// This shows a full config file!
module.exports = function (grunt) {
grunt.initConfig({
watch: {
files: "assets/scss/**/*.scss",
tasks: ['compass']
},
compass: {
dist: {
options: {
sassDir: 'assets/scss',
cssDir: 'assets/css',
outputStyle: 'compressed'
}
}
},
browserSync: {
dev: {
bsFiles: {
src : 'assets/css/*.css'
},
options: {
watchTask: true // < VERY important
}
}
}
});
// load npm tasks
grunt.loadNpmTasks('grunt-contrib-compass');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-browser-sync');
// start browsersync and then initiate the watch AFTER
grunt.registerTask('default', ["browserSync", "watch"]);
};
关于node.js - grunt-browser-sync 疯狂 : opening multiple instances of the browser over and over again,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25472587/