utils.js 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  1. 'use strict'
  2. const path = require('path')
  3. const config = require('../config')
  4. const ExtractTextPlugin = require('extract-text-webpack-plugin')
  5. const packageConfig = require('../package.json')
  6. const HtmlWebpackPlugin = require('html-webpack-plugin');
  7. const merge = require('webpack-merge');
  8. const glob = require('glob');
  9. const pathSrc = path.resolve(__dirname, '../src'); // F:\webui\multiple-pages\demo\src
  10. const devPathSrc = path.resolve(__dirname, '../../../src'); // node_modules应用下
  11. // 指定开发模式下需要加载的模块(可以做到只加载当前模块,提高开发效率)
  12. // index模块(登录)为必须,all 为所有
  13. // index 销售 采购 规范 质量 生产 车间
  14. // ['index', 'sales', ' ', 'standard', 'qualityControl', 'produce', 'workshop',
  15. // 物流 进程 成本 报表 基础配置 系统配置
  16. // 'logistics', 'process', ' ', 'reportform', 'basicconfig', 'system']
  17. let devModules = ['all'];
  18. if (pathSrc.indexOf('node_modules') > -1) {
  19. devModules = require('../../../cors.js').devModules;
  20. }
  21. // 获取入口集合
  22. const getEntries = function (suffix, polyfill) {
  23. // 自动获取
  24. const entryHtml = glob.sync(pathSrc + '/views/**/app.html'); // 根据html来
  25. const devEntryHtml = glob.sync(devPathSrc + '/views/**/app.html'); // 根据html来
  26. const entries = {};
  27. let setEntries = function (filePath, _chunk) {
  28. _chunk = _chunk.substring(0, _chunk.lastIndexOf('/'));
  29. let flag = true;
  30. flag = false;
  31. for (let item of devModules) {
  32. if (item && (_chunk.indexOf('views/' + item) >= 0 || item === 'all')) {
  33. flag = true;
  34. break;
  35. }
  36. }
  37. if (flag) {
  38. let arr = _chunk.split('/'),
  39. larr = [],
  40. rarr = [];
  41. console.log('arr: ', arr);
  42. larr = arr.slice(0, 2);
  43. _chunk = larr.join('/');
  44. if (arr.length > 2) {
  45. rarr = arr.slice(2, arr.length);
  46. _chunk = _chunk + '/' + rarr.join('-');
  47. }
  48. if (suffix) {
  49. filePath = filePath.replace('.html', suffix);
  50. }
  51. if (polyfill) {
  52. entries[_chunk] = ['babel-polyfill', filePath];
  53. } else {
  54. entries[_chunk] = filePath;
  55. }
  56. }
  57. }
  58. entryHtml.forEach((filePath) => {
  59. // views/index/app.html --> views/index chunk有'/'则js/css会有相应的目录
  60. let _chunk = filePath.split(pathSrc.replace(/\\/g, '/') + '/')[1]; // views/index/app.html
  61. setEntries(filePath, _chunk);
  62. });
  63. devEntryHtml.forEach((filePath) => {
  64. // views/index/app.html --> views/index chunk有'/'则js/css会有相应的目录
  65. let _chunk = filePath.split(devPathSrc.replace(/\\/g, '/') + '/')[1]; // views/index/app.html
  66. setEntries(filePath, _chunk);
  67. });
  68. return entries;
  69. };
  70. // 多入口配置(入口JS固定为main.js)
  71. exports.entries = function () {
  72. // ['babel-polyfill', './src/main.js']
  73. let _entries = getEntries('.js', true);
  74. return _entries;
  75. };
  76. //多页面输出配置
  77. exports.htmlPlugins = function () {
  78. let entryHtmls = getEntries('.html');
  79. let arr = [];
  80. for (let _chunk in entryHtmls) {
  81. console.log('loading chunk:', _chunk);
  82. // _chunk :views/index/index
  83. let conf = {
  84. favicon: pathSrc + '/assets/img/favicon.ico', //favicon路径,通过webpack引入同时可以生成hash值
  85. template: entryHtmls[_chunk], // html模板路径
  86. // filename: 'views/' + fileName, // 生成的html存放路径,相对于path
  87. filename: _chunk + '.html',
  88. chunks: [_chunk],
  89. inject: true // js插入的位置,true/'head'/'body'/false
  90. };
  91. if (process.env.NODE_ENV === 'production') {
  92. console.log('package content: ', _chunk)
  93. conf = merge(conf, {
  94. chunks: ['manifest', 'vendor', _chunk],
  95. minify: {
  96. // removeAttributeQuotes: true, // 删除可删除的引号
  97. removeComments: true, // 移除HTML中的注释
  98. collapseWhitespace: true // 删除空白符与换行符
  99. },
  100. chunksSortMode: 'dependency'
  101. })
  102. }
  103. arr.push(new HtmlWebpackPlugin(conf));
  104. }
  105. console.log('arr:', arr);
  106. return arr;
  107. };
  108. exports.assetsPath = function (_path) {
  109. const assetsSubDirectory = process.env.NODE_ENV === 'production' ?
  110. config.build.assetsSubDirectory :
  111. config.dev.assetsSubDirectory
  112. return path.posix.join(assetsSubDirectory, _path)
  113. }
  114. exports.cssLoaders = function (options) {
  115. options = options || {}
  116. const cssLoader = {
  117. loader: 'css-loader',
  118. options: {
  119. sourceMap: options.sourceMap
  120. }
  121. }
  122. const postcssLoader = {
  123. loader: 'postcss-loader',
  124. options: {
  125. sourceMap: options.sourceMap
  126. }
  127. }
  128. // generate loader string to be used with extract text plugin
  129. function generateLoaders(loader, loaderOptions) {
  130. const loaders = options.usePostCSS ? [cssLoader, postcssLoader] : [cssLoader]
  131. if (loader) {
  132. loaders.push({
  133. loader: loader + '-loader',
  134. options: Object.assign({}, loaderOptions, {
  135. sourceMap: options.sourceMap
  136. })
  137. })
  138. }
  139. // Extract CSS when that option is specified
  140. // (which is the case during production build)
  141. if (options.extract) {
  142. return ExtractTextPlugin.extract({
  143. use: loaders,
  144. // 解决打包后背景图片路径不对的问题
  145. // static/css/views/index/index.css
  146. // ../../../../static/img/xx.jpg
  147. publicPath: '../../../', // 注意: 此处根据路径, 自动更改
  148. fallback: 'vue-style-loader'
  149. })
  150. } else {
  151. return ['vue-style-loader'].concat(loaders)
  152. }
  153. }
  154. // https://vue-loader.vuejs.org/en/configurations/extract-css.html
  155. return {
  156. css: generateLoaders(),
  157. postcss: generateLoaders(),
  158. less: generateLoaders('less'),
  159. sass: generateLoaders('sass', {
  160. indentedSyntax: true
  161. }),
  162. scss: generateLoaders('sass'),
  163. stylus: generateLoaders('stylus'),
  164. styl: generateLoaders('stylus')
  165. }
  166. }
  167. // Generate loaders for standalone style files (outside of .vue)
  168. exports.styleLoaders = function (options) {
  169. const output = []
  170. const loaders = exports.cssLoaders(options)
  171. for (const extension in loaders) {
  172. const loader = loaders[extension]
  173. output.push({
  174. test: new RegExp('\\.' + extension + '$'),
  175. use: loader
  176. })
  177. }
  178. return output
  179. }
  180. exports.createNotifierCallback = () => {
  181. const notifier = require('node-notifier')
  182. return (severity, errors) => {
  183. if (severity !== 'error') return
  184. const error = errors[0]
  185. const filename = error.file && error.file.split('!').pop()
  186. notifier.notify({
  187. title: packageConfig.name,
  188. message: severity + ': ' + error.name,
  189. subtitle: filename || '',
  190. icon: path.join(__dirname, 'logo.png')
  191. })
  192. }
  193. }