通过搭建自己的npm脚本实现前端工作自动化构建压缩以及支持ES6模块化
并且不依赖webpack和gulp哦~~~~~~~~~~~
步骤
按名称保存本页的文件
1 npm install
2 npm run dev 开发
3 npm run build 打包
这里简要说明一下
package.json非常熟悉就是一些经常用的依赖
postcss.config.js 这个文件是postcss默认的config文件功能是压缩dist/css文件夹下所有的css
create.js 它的作用是初始化并创建dist和src两个文件夹 和里面的一些初始化文件
jsmini.js 它的作用是压缩src/js里所有的js 输出到dist/js
.babelrc 它的作用是编译ES6
rollup.config.dev.js 它的作用是支持ES6的模块化打包 默认你的工作区的js入口是src/js/main.js 会被打包成src/js/bundle.js.也就是说你在main.js里所import的模块 最终都被打进bundle.js. 页面需要引用的是src/js/bundle.js
如果要在页面啊引入npm安装的包 ,就打开rollup.config.dev.js
例如jquery 请这样添加external: ['$',path.resolve( './node_modules/jquery' ),'_',path.resolve('./node_modules/underscore')] ,然后在js里就可以import $ from 'jquery'了
github地址 https://github.com/174744813/html-simple-build-tools
package.json
{
"name": "npm",
"version": "1.0.0",
"description": "",
"main": "index.js",
"config": {
"jsdir": "./src/js/"
},
"scripts": {
"predev": "echo '开始创建并初始化'",
"css": "postcss ./src/css/*.css -d ./dist/css",
"js": "node jsmini.js",
"images": "imagemin src/images/* --out-dir=dist/images/",
"html": "node _html.js",
"dev": "node create.js",
"httpserver": "cd src&&browser-sync start --server --files \"css/*.css, images/*.png,images/*.jpg, *.html\" ",
"httpserver_build": "cd dist&&browser-sync start --server --files \"css/*.css, images/*.png,images/*.jpg, *.html\" ",
"rollup": "rollup -c rollup.config.dev.js --watch",
"build": "npm-run-all css js images html httpserver_build"
},
"author": "wangxu",
"license": "ISC",
"devDependencies": {
"autoprefixer": "^7.2.1",
"babel-cli": "^6.26.0",
"babel-preset-env": "^1.6.1",
"babel-preset-es2015-rollup": "^3.0.0",
"browser-sync": "^2.18.13",
"chalk": "^2.3.0",
"chokidar": "^1.7.0",
"cp-file": "^5.0.0",
"cross-var": "^1.1.0",
"cssnano": "^3.10.0",
"filedir": "^1.0.1",
"imagemin-cli": "^3.0.0",
"npm-run-all": "^4.1.2",
"postcss-cli": "^4.1.1",
"rollup": "^0.52.2",
"rollup-plugin-babel": "^3.0.2",
"rollup-plugin-commonjs": "^8.2.6",
"rollup-plugin-json": "^2.3.0",
"rollup-plugin-node-resolve": "^3.0.0",
"shelljs": "^0.7.8",
"uglify-es": "^3.2.2"
},
"dependencies": {
"jquery": "^3.2.1",
"underscore": "^1.8.3"
}
}
_html.js
var filedir=require("filedir");
var path = require("path");
var fs = require("fs");
var cpFile = require('cp-file');
var src='./src'
var dist='./dist'
fs.readdir(src,function(err,files){
var result=[];
var files_=files.filter(function(item,index){
return item.indexOf(".html")!=(-1)
})
files_.forEach(function(item,index){
cpFile(src+'/'+item, dist+'/'+item)
})
})
create.js
var fs = require("fs");
var http = require('http')
var filedir=require("filedir");
var path = require("path");
var shelljs=require("shelljs")
var chalk=require("chalk")
var http = require("http");
var fs = require("fs");
var request = require('request');
function get_js(url,address){
http.get(url, function (response) {
response.setEncoding('binary'); //二进制binary
var Data = '';
response.on('data', function (data) { //加载到内存
Data += data;
}).on('end', function () { //加载完
filedir.write(address, Data );
})
})
}
//
function get_logo(){
var arttemplate = filedir.read('http://imgs.aixifan.com/live/1482597494735/1482597494735.jpg')
filedir.write('./src/images/logo.jpg',src=arttemplate)
}
var Prompt={
dist:{src:"./dist",text:"开始创建dist文件夹"},
dist_css:{src:"./dist/css",text:"开始创建dist/css"},
dist_images:{src:"./dist/images",text:"开始创建dist/images"},
dist_js:{src:"./dist/js",text:"开始创建dist/js"},
src:{src:"./src",text:"开始创建src文件夹"},
src_css:{src:"./src/css",text:"开始创建src/css"},
src_images:{src:"./src/images",text:"开始创建src/images"},
src_js:{src:"./src/js",text:"开始创建src/js"},
src_index_html:{src:"./src/index.html",text:"开始创建src/index.html"}
}
Object.prototype.hasO=Object.prototype.hasOwnProperty
function judge(){
var this_=this
for(var i in this_){
if(this_.hasO(i)){
if(!filedir.isDir(this_[i].src)){
var te_name=this_[i].src.split(".");
te_name=te_name[te_name.length-1];
var for_css=this_[i].src.split("/")
for_css=for_css[for_css.length-1]
if(te_name=="html"&&filedir.isFile(this_[i].src) ){
console.log(chalk.yellow("因为已经有"+this_[i].src+",故不会再创建"))
continue
}
if(te_name=="html"&&!(filedir.isFile(this_[i].src)) ){
console.log(chalk.green(this_[i].text));
fs.writeFileSync(this_[i].src,
"<!DOCTYPE html>\n"+
"<html lang=\"en\" style='height:100%;position:relative'>\n"+
"<head>\n"+
"<meta charset=\"UTF-8\">\n"+
"<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n"+
"<meta http-equiv=\"X-UA-Compatible\" content=\"ie=edge\">\n"+
"<title>Document</title>\n"+
"<link rel=\"stylesheet\" href=\"./css/main.css\">"+
"</head>\n"+
"<body style='height:100%;position:relative'><div class='logobox' style='width:600px;height:425px;position: absolute;left: 0;right: 0;margin: auto;top: 50%;margin-top: -212px;'><img style='max-width:100%' src='https://s1.ax1x.com/2017/12/14/qjYxe.md.jpg'><h5 style='text-align:center;line-height:90px;font-size: 45px;color:gray'>Welcome to use front end build tools</h5></div></body>\n"+
"</html>\n"
)
continue
}else{
console.log(chalk.green(this_[i].text));
fs.mkdirSync(this_[i].src);
}
if(for_css=="css"&&i=="src_css"){
fs.writeFileSync("./src/css/main.css",
"*{padding:0;margin:0}\n"+
"a{text-decoration:none}\n"+
"ul,ol{list-style:none}\n"+
"img{border:none}\n"+
"br{font-size:0;line-height:0;clear:both}"
)
}
if(for_css=="js"&&i=="src_js"){
fs.writeFileSync("./src/js/main.js","")
}
}
}
}
}
judge.call(Prompt)
if(!filedir.isFile("./.babelrc")){
console.log(chalk.green("开始创建.babelrc"))
filedir.write('./.babelrc',"{\"presets\": [[\"es2015\", { \"modules\": false }]],\"plugins\" : [ ]}")
}
if(!filedir.isFile("./postcss.config.js")){
console.log(chalk.green("开始创建postcss.config.js"))
filedir.write("./postcss.config.js","module.exports = {plugins: [require('autoprefixer'),require('cssnano')({preset: 'default' }),],}")
}
console.log(chalk.cyan(
"-------------------\n"+
"所有文件初始化完毕完毕\n"+
"-------------------\n"
))
//===============================================================================================
console.log(chalk.cyan(
"-------------------\n"+
"等待监听启动,open Browser...\n"+
"-------------------\n"
))
//===============================================================================================
shelljs.exec("npm-run-all --parallel httpserver rollup")
jsmini.js
var fs = require('fs');
var min=require("uglify-es")
var packageJSON=fs.readFileSync('./package.json', 'utf8')
packageJSON=JSON.parse(packageJSON)
var jsdir=packageJSON.config.jsdir;
fs.readdir(jsdir,function(err,files){
var result=[];
files.forEach(function(item,index){
result.push(jsdir+item)
})
buildOne(result)
})
function buildOne(fileIn) {
for (var i = 0,len = fileIn.length; i < len; i++) {
var origCode = fs.readFileSync(fileIn[i], 'utf8');
var dist_=fileIn[i].replace(/src/,'dist')
var result=min.minify(origCode)
fs.writeFileSync(dist_, result.code, 'utf8');
};
}
rollup.config.dev.js
import babel from 'rollup-plugin-babel';
import json from 'rollup-plugin-json';
import resolve from 'rollup-plugin-node-resolve';
import commonjs from 'rollup-plugin-commonjs';
import path from 'path'
export default {
input: 'src/js/main.js',
external: ['$',path.resolve( './node_modules/jquery' ),'_',path.resolve('./node_modules/underscore')],
output: {
file: 'src/js/bundle.js',
format: 'iife'
},
plugins: [
json(),
babel(),
resolve({
jsnext: true,
main: true,
browser: true,
}),
commonjs()
]
};
网友评论