Jquery, React, vue, typescript
preface
Because this article focuses on the introduction of gulP4.0 scaffolding ideas, the use of related plug-ins and the design of the project structure, because the basic use of GULP is very simple, if you are not familiar with can move to the official website to study. The design ideas and functions of the scaffold are as follows:
Description of third-party plug-ins used in scaffolding
- Gulp-jshint — js syntax detection
- Gulp-util — The terminal console prints custom error messages
- Http-proxy-middleware — Set up a proxy to work with gulp-Connect
- Gulp-less — compiles less into CSS
- Gulp-file-include — Used to import modularized files, such as the common parts, in the include mode
- Gulp-connect — Used to start the local server
- Gulp-clean — Clears a directory
- Gulp-uglify — Compresses JS
- Gulp-minify-css — Compresses CSS
- Gulp -autoprefixer – automatically adds the browser prefix
- Imagemin-pngquant — PNG image compression
- Gulp-imagemin — Image compression
- Gulp-cache – Sets the cache of gulp packages, usually used for IMG
- Gulp-md5-plus — Md5 processing of file names for easy packaging and update
Of course, there are many common plugins that gulp can use to make the project better, and you can integrate your own plugins to make the project better.
Project Catalog Design
1. The SRC directory, which is the source directory of our development project, is structured as follows:
2. Dist directory, that is, the output directory, the specific structure is as follows:
I would like to point out that I have made a special treatment on this section because the packaging of GULp-MD5-Plus is sometimes unstable and the CORRESPONDING MD5 suffix may not be automatically added to HTML. If you have a better solution in your work, please contact me in time.
3. Configure gulpfile
Since we want to distinguish between the development and production environments, we use two different configuration files here, depending on NODE_ENV.
Scaffold complete source code (some plug-ins and configurations are annotated in detail)
- config.js
module.exports = {
dist: './dist/static'.// Configure the build directory
}
Copy the code
- gulp.dev.js
const gulp = require('gulp');
// js
const Jshint = require("gulp-jshint"); / / js check
const Gutil = require('gulp-util');
const Proxy = require('http-proxy-middleware');
// const Webpack = require('webpack');
// const WebpackConfig = require('./webpack.config.js');
// css
const Less = require('gulp-less'); / / compile less
// html
const FileInclude = require('gulp-file-include'); // File modularity
// server
const Connect = require('gulp-connect'); // Introduce the gulp-connect module
const Clean = require('gulp-clean'); // Clean up the directory
// Configuration file
const config = require('./config');
const { dist } = config;
// html
async function html() {
return gulp.src('src/views/*.html')
.pipe(FileInclude({ // HTML template replacement, see below for details
prefix: '# #'.basepath: '@file'
})).on('error'.function(err) {
console.error('Task:copy-html,', err.message);
this.end();
})
.pipe(gulp.dest(dist)) / / copy
.pipe(Connect.reload())
}
// css
async function css() {
return await gulp.src('src/css/*.less')
.pipe(Less()) / / compile less
.pipe(gulp.dest(dist + '/css')) // The current CSS file
.pipe(Connect.reload());/ / update
}
// js
// const compilerJS = Webpack(WebpackConfig);
async function js() {
return await gulp.src('src/js/**')
.pipe(Jshint())// Check the code
// .pipe(Babel({
// presets: ['es2015']
// }))
.on('error'.function(err) {
Gutil.log(Gutil.colors.red('[Error]'), err.toString());
})
.pipe(gulp.dest(dist + '/js')) / / copy
.pipe(Connect.reload()); / / update
// Using ES6 + can be configured separately
// compilerJS.run(function(err, stats) {
// if(err) throw new Gutil.PluginError("webpack:js", err);
// Gutil.log("[webpack]", stats.toString({
// colors: true
/ /}));
// cb()
// });
}
// image
async function image() {
return await gulp.src('src/images/*')
.pipe(gulp.dest(dist + '/images'));
}
// clean dir
async function clean() {
AllowEmpty: true: File not found with Singular Glob
return await gulp.src(dist, {allowEmpty: true}).pipe(Clean());
}
// Server function
async function server() {
Connect.server({
root:dist, / / root directory
// IP :'192.168.11.62', default localhost:8080
livereload:true.// Automatic update
port:9909./ / port
middleware: function(connect, opt) {
return [
Proxy('/api', {
target: 'http://localhost:8080'.changeOrigin:true
}),
Proxy('/otherServer', {
target: 'http://IP:Port'.changeOrigin:true})]}})}module.exports = {
html,
css,
js,
image,
clean,
server
}
Copy the code
- gulp.prod.js
const gulp = require('gulp');
// const Rename = require('gulp-rename'); / / renamed
// js
const Uglify = require('gulp-uglify'); Js / / compression
// const Babel = require('gulp-babel');
// css
const Minifycss = require('gulp-minify-css'); / / compress CSS
const Less = require('gulp-less'); / / compile less
const Autoprefixer = require('gulp-autoprefixer'); // The browser prefix
// html
const MinifyHtml = require("gulp-minify-html"); HTML / / compression
const FileInclude = require('gulp-file-include'); // File modularity
// image
const Imagemin = require('gulp-imagemin');
const Pngquant = require('imagemin-pngquant'); // PNG image compression plugin
const Cache = require('gulp-cache');
const Clean = require('gulp-clean'); // Clean up the directory
To prevent the browser from reading the old cache file, add an MD5 stamp to the md5 version
const md5 = require("gulp-md5-plus");
const config = require('./config');
const { dist } = config;
// html
async function html() {
return gulp.src('src/views/*.html')
.pipe(FileInclude({ // HTML template replacement, see below for details
prefix: '# #'.basepath: '@file'
}))
// .pipe(MinifyHtml())
.on('error'.function(err) {
console.error('Task:copy-html,', err.message);
this.end();
})
.pipe(gulp.dest(dist)) / / copy
}
// css
async function css() {
return await gulp.src('src/css/**')
.pipe(Less()) / / compile less
.pipe(Autoprefixer({
cascade: true.// Whether to beautify the property value by default: true like this:
//-webkit-transform: rotate(45deg);
// transform: rotate(45deg);
remove: true // Whether to remove unnecessary prefixes. Default: true
}))
.pipe(Minifycss({ / / compress CSS
// Type: Boolean Default: true [whether to enable advanced optimization (merge selectors, etc.)]
advanced: true.// Keep ie7 and the following compatible writing types: String Default: 'or'*' [Enable compatibility mode; 'IE7' : IE7 compatibility mode, 'IE8' : IE8 compatibility mode, '*' : IE9+ compatibility mode]
compatibility: ' '.// Type: Boolean Default: false [whether to keep newlines]
keepBreaks: false.// Keep all special prefixes when you generate browser prefixes with Autoprefixer. If you don't use this parameter, it is possible to delete some of your prefixes
keepSpecialComments: The '*'
}))
.pipe(gulp.dest(dist + '/css'))
.pipe(md5(10, dist + '/*.html', {
mappingFile: 'manifest.json'.connector: '. ' // The connection between the file name and hash
}))
.pipe(gulp.dest(dist + '/css')) // The current CSS file
}
// js
async function js() {
return await gulp.src('src/js/**')
// .pipe(Babel({
// presets: ['es2015']
// }))
.pipe(Uglify()) Js / / compression
.pipe(gulp.dest(dist + '/js'))
.pipe(md5(10, dist + '/*.html', {
mappingFile: 'manifest.json'.connector: '. '
}))
.pipe(gulp.dest(dist + '/js')) / / copy
}
// image
async function image() {
return await gulp.src('src/images/*')
.pipe(Cache(Imagemin({
optimizationLevel: 5.Type: Number Default: 3 Value range: 0-7 (optimization level)
progressive: true.// Type: Boolean Default: false Lossless compression of JPG images
interlaced: true.// Type: Boolean Default: false Interlaced scan GIF for rendering
multipass: true.// Type: Boolean Default: false Optimize SVG several times until it is fully optimized
svgoPlugins: [{removeViewBox: false}].// Do not remove the SVG viewbox property
use: [Pngquant()] // Use pngQuant to deep compress PNG images imagemin plugin
})))
.pipe(gulp.dest(dist + '/images'));
}
// clean dir
async function clean() {
AllowEmpty: true: File not found with Singular Glob
return await gulp.src(dist, {allowEmpty: true}).pipe(Clean());
}
module.exports = {
html,
css,
js,
image,
clean
}
Copy the code
- gulpfile.js
const gulp = require('gulp');
// Import different configuration files depending on the environment
let buildConfig;
if(process.env.NODE_ENV === 'dev') {
buildConfig = require('./build/gulp.dev');
gulp.task('server', buildConfig.server); // Local service
} else {
buildConfig = require('./build/gulp.prod');
// gulp.task('md5', gulp.series(buildConfig.md5Css, buildConfig.md5Js));
gulp.task('clean', buildConfig.clean); // Clean up the directory
}
gulp.task('html', buildConfig.html); / / pack to HTML
gulp.task('js', buildConfig.js); / / packaging js
gulp.task('css', buildConfig.css); / / packaging CSS
gulp.task('images', buildConfig.image); / / packaging image
gulp.task('sources', gulp.series('html', gulp.parallel('js'.'css'.'images')));
// Listen for file changes
gulp.task('watch'.async () => {
gulp.watch('src/views/*', gulp.series('html')); // Listen for HTML changes
gulp.watch('src/js/**', gulp.series('js')); // Listen for js changes
gulp.watch('src/css/*', gulp.series('css')); // Listen for CSS changes
gulp.watch('src/images/*', gulp.series('images')); // Listen for image changes
});
// build
if(process.env.NODE_ENV === 'dev') {
gulp.task('dev', gulp.series('sources'.'server'.'watch'));
} else {
gulp.task('build', gulp.series('sources'));
}
Copy the code
- package.json
{
"dependencies": {
"@babel/core": "^ 7.4.5"."babel-preset-es2015": "^ 6.24.1"."gulp": "^ 4.0.2." "."gulp-autoprefixer": "^ 6.1.0"."gulp-babel": "^ 8.0.0." "."gulp-cache": "^ 1.1.2." "."gulp-clean": "^ 0.4.0"."gulp-connect": "^ 5.7.0"."gulp-file-include": "^ 2.0.1." "."gulp-imagemin": "^ 6.0.0"."gulp-jshint": "^ 2.1.0." "."gulp-less": "^ 4.0.1." "."gulp-md5-plus": "^ 1.0.3"."gulp-minify-css": "^ 1"."gulp-minify-html": "^ 1.0.6"."gulp-rename": "^ 1.4.0." "."gulp-uglify": "^ 3.0.2." "."gulp-util": "^ 3.0.8"."http-proxy-middleware": "^ 0.19.1." "."http-server": "^ 0.11.1"."imagemin-pngquant": "^ 8.0.0." "."jshint": "^ 2.10.2"."jsonfile": "^ 5.0.0"."webpack": "^ 4.35.2"
},
"scripts": {
"start": "NODE_ENV=dev gulp dev"."build": "NODE_ENV=prod gulp clean && gulp build"."serve": "http-server dist/static -p 3000"
},
"devDependencies": {}}Copy the code
For complete source code and demo, go to gulp4_multi_pages.
The last
The scaffold still needs to be improved, such as how to be compatible with Uglify and Babel,md5 needs to be used twice, if there is a better solution, please feel free to communicate. In the scaffold selection, also does not have to use gulp, webpack, general experience is the traditional static website suitable for gulp, because there is no need to compile ES6, so there is a smaller volume, of course, you can also use Webpack, this article is to provide you with a use of GULP4 scaffolding ideas, hope to gain.
More recommended
- How to write your own JS library in less than 200 lines of code
- A summary of common JS functions that make you more productive in an instant
- A picture shows you how to play vue-Cli3 quickly
- 3 minutes teach you to use native JS implementation with progress listening file upload preview component
- 3 minutes teach you to use native JS implementation with progress listening file upload preview component
- Developing travel List with Angular8 and Baidu Maps API
- Js basic search algorithm implementation and 1.7 million data under the performance test
- How to make front-end code 60 times faster
- Front End Algorithm series array deweighting
- Vue Advanced Advanced series – Play with Vue and vuex in typescript
- In the first three years, talk about the top five books worth reading
Welcome to follow the public account below to get more front-end knowledge and learning community:
To restore the learning path, the author will acquire the mind map of the front-end learning path for many years of experience