utils.js 6.7 KB

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