Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

NPM Script实现work flow自动化 #4

Open
nie-xin opened this issue Feb 14, 2016 · 0 comments
Open

NPM Script实现work flow自动化 #4

nie-xin opened this issue Feb 14, 2016 · 0 comments
Labels

Comments

@nie-xin
Copy link
Owner

nie-xin commented Feb 14, 2016

之前在做SPA的时候,我比较偏向用Webpack或Brunch这样的工具来实现workflow自动化。当对于一个流程复杂的重前端项目,这样的专业工具虽然配置复杂,但确实能实现许多复杂精确的操作。

本来以为现在手上的这个小的网站项目不需要自动化,快糙猛地搞完就行了。没想到市场组要求越来越多,WordPress的整合也比我预想的复杂,于是趁这个周末赶紧补上一个自动化工作流以节省时间。

但和之前比起来,这个工作流确实可以称得上简单。没有太多的dependency,原生HTML、JS和CSS。其中HTML模板的优化由PHP完成,要处理也只剩下JS和CSS而已了。

为这样简单的工作流上Webpack有些得不偿失,于是直接用NPM Script实现了一个 。让我们先从使用到的NPM模块看起:

  "devDependencies": {
    "browser-sync": "^2.11.1",
    "clean-css": "^3.4.9",
    "uglify-js": "^2.6.1",
    "watch": "^0.17.1"
  }

如上所述,主要处理的是CSS(clean-css)和JS(uglify-js)。外加了一个自动刷新浏览器的browser sync和监控文件改动的watch。

下面就是实际使用的script了:

  "scripts": {
    "browserSync": "browser-sync start --proxy --files './**/*.css, ./**/*.php, ./**/*.js'",
    "uglifyjs": "uglifyjs js/*.js > script.min.js",
    "cleancss": "cleancss -o style.min.css style.css",
    "build": "npm run uglifyjs && npm run cleancss",
    "watch": "watch 'npm run build' . --filter='watchIgnore.js'"
  }

够简单吧?使用npm run browserSync来重载浏览器,使用npm run watch来实时构建项目。

这里需要注意的是browser sync要求在body tag之前插入一堆injection代码,我在这里使用PHP检测当前环境,只在localhost的情况下插入,避免代码泄露。

另外可以看到watch的CLI带了一个奇怪的watchIgnore.js文件,这主要是因为我的观测目录同时也是构建,为了避免循环构建加入一个过滤函数来过滤script.min.js和style.min.css(watch的CLI还是过于简单了,其实加个except选项不就好了……)。当你的构建目录和观测目录不一样时可省略这个选项。

除了直接NPM Script外,也可以写一个小的node script来做这些工作,本质上也比较接近其他构建工具了。

这个工作流还不完善,至少还需要加入部署至staging的部分,等我完成后补上。

这里有一份addyosmani维护的常用NPM Script模板,可供参考。

@nie-xin nie-xin added the 积累 label Mar 24, 2016
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant