webpack.common.ts 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452
  1. import FriendlyErrorsWebpackPlugin from '@soda/friendly-errors-webpack-plugin';
  2. import BilldHtmlWebpackPlugin, { logData } from 'billd-html-webpack-plugin';
  3. import CopyWebpackPlugin from 'copy-webpack-plugin';
  4. import ESLintPlugin from 'eslint-webpack-plugin';
  5. import HtmlWebpackPlugin from 'html-webpack-plugin';
  6. import MiniCssExtractPlugin from 'mini-css-extract-plugin';
  7. import { NaiveUiResolver } from 'unplugin-vue-components/resolvers';
  8. import ComponentsPlugin from 'unplugin-vue-components/webpack';
  9. import { VueLoaderPlugin } from 'vue-loader';
  10. import { Configuration, DefinePlugin } from 'webpack';
  11. import { BundleAnalyzerPlugin } from 'webpack-bundle-analyzer';
  12. import { merge } from 'webpack-merge';
  13. import WebpackBar from 'webpackbar';
  14. import WindiCSSWebpackPlugin from 'windicss-webpack-plugin';
  15. import {
  16. analyzerEnable,
  17. eslintEnable,
  18. htmlWebpackPluginTitle,
  19. outputDir,
  20. outputStaticUrl,
  21. webpackBarEnable,
  22. windicssEnable,
  23. } from '../constant';
  24. import { chalkINFO, chalkWARN } from '../utils/chalkTip';
  25. import { resolveApp } from '../utils/path';
  26. import devConfig from './webpack.dev';
  27. import prodConfig from './webpack.prod';
  28. console.log(chalkINFO(`读取: ${__filename.slice(__dirname.length + 1)}`));
  29. const sassRules = (isProduction: boolean, module?: boolean) => {
  30. return [
  31. isProduction
  32. ? {
  33. loader: MiniCssExtractPlugin.loader,
  34. options: {
  35. publicPath: outputStaticUrl(isProduction),
  36. },
  37. }
  38. : {
  39. loader: 'vue-style-loader',
  40. options: {
  41. sourceMap: false,
  42. },
  43. },
  44. {
  45. loader: 'css-loader', // 默认会自动找postcss.config.js
  46. options: {
  47. importLoaders: 2, // https://www.npmjs.com/package/css-loader#importloaders
  48. sourceMap: false,
  49. modules: module
  50. ? {
  51. localIdentName: '[name]_[local]_[hash:base64:5]',
  52. }
  53. : undefined,
  54. },
  55. },
  56. {
  57. loader: 'postcss-loader', // 默认会自动找postcss.config.js
  58. options: {
  59. sourceMap: false,
  60. },
  61. },
  62. {
  63. loader: 'sass-loader',
  64. options: {
  65. sourceMap: false,
  66. // 根据sass-loader9.x以后使用additionalData,9.x以前使用prependData
  67. additionalData: `@use 'billd-scss/src/index.scss' as *;@import '@/assets/constant.scss';`,
  68. },
  69. },
  70. ].filter(Boolean);
  71. };
  72. const cssRules = (isProduction: boolean, module?: boolean) => {
  73. return [
  74. isProduction
  75. ? {
  76. loader: MiniCssExtractPlugin.loader,
  77. options: {
  78. publicPath: outputStaticUrl(isProduction),
  79. },
  80. }
  81. : {
  82. loader: 'vue-style-loader',
  83. options: {
  84. sourceMap: false,
  85. },
  86. },
  87. {
  88. loader: 'css-loader', // 默认会自动找postcss.config.js
  89. options: {
  90. importLoaders: 1, // https://www.npmjs.com/package/css-loader#importloaders
  91. sourceMap: false,
  92. modules: module
  93. ? {
  94. localIdentName: '[name]_[local]_[hash:base64:5]',
  95. }
  96. : undefined,
  97. },
  98. },
  99. {
  100. loader: 'postcss-loader', // 默认会自动找postcss.config.js
  101. options: {
  102. sourceMap: false,
  103. },
  104. },
  105. ].filter(Boolean);
  106. };
  107. const commonConfig = (isProduction) => {
  108. const result: Configuration = {
  109. entry: {
  110. main: {
  111. import: './src/main.ts',
  112. },
  113. },
  114. output: {
  115. clean: true, // 在生成文件之前清空 output 目录。替代clean-webpack-plugin
  116. filename: 'js/[name]-[contenthash:6]-bundle.js', // 入口文件打包生成后的文件的文件名
  117. /**
  118. * 入口文件中,符合条件的代码,被抽离出来后生成的文件的文件名
  119. * 如:动态(即异步)导入,默认不管大小,是一定会被单独抽离出来的。
  120. * 如果一个模块既被同步引了,又被异步引入了,不管顺序(即不管是先同步引入再异步引入,还是先异步引入在同步引入),
  121. * 这个模块会打包进bundle.js,而不会单独抽离出来。
  122. */
  123. chunkFilename: 'js/[name]-[contenthash:6]-bundle-chunk.js',
  124. path: resolveApp(`./${outputDir}`),
  125. assetModuleFilename: 'assets/[name]-[contenthash:6].[ext]', // 静态资源生成目录(不管什么资源默认都统一生成到这里,除非单独设置了generator)
  126. /**
  127. * webpack-dev-server 也会默认从 publicPath 为基准,使用它来决定在哪个目录下启用服务,来访问 webpack 输出的文件。
  128. * 所以不管开发模式还是生产模式,output.publicPath都会生效,
  129. * output的publicPath建议(或者绝大部分情况下必须)与devServer的publicPath一致。
  130. * 如果不设置publicPath,它默认就约等于output.publicPath:"",到时候不管开发还是生产模式,最终引入到
  131. * index.html的所有资源都会拼上这个路径,如果不设置output.publicPath,会有问题:
  132. * 比如vue的history模式下,如果不设置output.publicPath,如果路由全都是/foo,/bar,/baz这样的一级路由没有问题,
  133. * 因为引入的资源都是js/bundle.js,css/bundle.css等等,浏览器输入:http://localhost:8080/foo,回车访问,
  134. * 引入的资源就是http://localhost:8080/js/bundle.js,http://localhost:8080/css/bundle.css,这些资源都
  135. * 是在http://localhost:8080/根目录下的没问题,但是如果有这些路由:/logManage/logList,/logManage/logList/editLog,
  136. * 等等超过一级的路由,就会有问题,因为没有设置output.publicPath,所以它默认就是"",此时浏览器输入:
  137. * http://localhost:8080/logManage/logList回车访问,引入的资源就是http://localhost:8080/logManage/logList/js/bundle.js,
  138. * 而很明显,我们的http://localhost:8080/logManage/logList/js目录下没有bundle.js这个资源(至少默认情况下是没有,除非设置了其他属性)
  139. * 找不到这个资源就会报错,这种情况的路由是很常见的,所以建议默认必须手动设置output.publicPath:"/",这样的话,
  140. * 访问http://localhost:8080/logManage/logList,引入的资源就是:http://localhost:8080/js/bundle.js,就不会报错。
  141. * 此外,output.publicPath还可设置cdn地址。
  142. */
  143. publicPath: outputStaticUrl(isProduction),
  144. },
  145. cache: {
  146. type: 'memory',
  147. // type: 'filesystem',
  148. // allowCollectingMemory: true, // 它在生产模式中默认为false,并且在开发模式下默认为true。https://webpack.js.org/configuration/cache/#cacheallowcollectingmemory
  149. // buildDependencies: {
  150. // // 建议cache.buildDependencies.config: [__filename]在您的 webpack 配置中设置以获取最新配置和所有依赖项。
  151. // config: [
  152. // resolveApp('./script/config/webpack.common.ts'),
  153. // resolveApp('./script/config/webpack.dev.ts'),
  154. // resolveApp('./script/config/webpack.prod.ts'),
  155. // resolveApp('.browserslistrc'), // 防止修改了.browserslistrc文件后,但没修改webpack配置文件,webpack不读取最新更新后的.browserslistrc
  156. // resolveApp('babel.config.js'), // 防止修改了babel.config.js文件后,但没修改webpack配置文件,webpack不读取最新更新后的babel.config.js
  157. // ],
  158. // },
  159. },
  160. resolve: {
  161. // 解析路径
  162. extensions: ['.js', '.jsx', '.ts', '.tsx', '.vue', '.mjs'], // 解析扩展名,加上.mjs是因为vant,https://github.com/youzan/vant/issues/10738
  163. alias: {
  164. '@': resolveApp('./src'), // 设置路径别名
  165. script: resolveApp('./script'), // 设置路径别名
  166. vue$: 'vue/dist/vue.runtime.esm-bundler.js', // 设置vue的路径别名
  167. },
  168. fallback: {
  169. /**
  170. * webpack5移除了nodejs的polyfill,更专注于web了?
  171. * 其实webpack5之前的版本能用nodejs的polyfill,也是
  172. * 和nodejs正统的api不一样,比如path模块,nodejs的path,
  173. * __dirname是读取到的系统级的文件绝对路径的(即/user/xxx)
  174. * 但在webpack里面使用__dirname,读取到的是webpack配置的绝对路径/
  175. * 可能有用的polyfill就是crypto这些通用的模块,类似path和fs这些模
  176. * 块其实都是他们的polyfill都是跑在浏览器的,只是有这些api原本的一些功能,
  177. * 还是没有nodejs的能力,所以webpack5干脆就移除了这些polyfill,你可以通过
  178. * 安装他们的polyfill来实现原本webpack4之前的功能,但是即使安装他们的polyfill
  179. * 也只是实现api的功能,没有他们原本在node的能力
  180. */
  181. // path: require.resolve('path-browserify'),
  182. // path: false,
  183. // fs: false,
  184. // child_process: false,
  185. },
  186. },
  187. resolveLoader: {
  188. // 用于解析webpack的loader
  189. modules: ['node_modules'],
  190. },
  191. module: {
  192. noParse: /^(vue|vue-router)$/,
  193. // loader执行顺序:从下往上,从右往左
  194. rules: [
  195. {
  196. test: /\.vue$/,
  197. use: [
  198. {
  199. loader: 'vue-loader',
  200. },
  201. ],
  202. },
  203. {
  204. test: /\.css$/,
  205. oneOf: [
  206. {
  207. resourceQuery: /module/,
  208. use: cssRules(isProduction, true),
  209. },
  210. {
  211. resourceQuery: /\?vue/,
  212. use: cssRules(isProduction),
  213. },
  214. {
  215. test: /\.module\.\w+$/,
  216. use: cssRules(isProduction, true),
  217. },
  218. {
  219. use: cssRules(isProduction),
  220. },
  221. ],
  222. sideEffects: true, // 告诉webpack是有副作用的,不对css进行删除
  223. },
  224. {
  225. test: /\.(sass|scss)$/,
  226. oneOf: [
  227. {
  228. resourceQuery: /module/,
  229. use: sassRules(isProduction, true),
  230. },
  231. {
  232. resourceQuery: /\?vue/,
  233. use: sassRules(isProduction),
  234. },
  235. {
  236. test: /\.module\.\w+$/,
  237. use: sassRules(isProduction, true),
  238. },
  239. {
  240. use: sassRules(isProduction),
  241. },
  242. ],
  243. sideEffects: true,
  244. },
  245. {
  246. test: /\.(jpg|jpeg|png|gif|svg|webp)$/,
  247. type: 'asset',
  248. generator: {
  249. filename: 'img/[name]-[contenthash:6][ext]',
  250. },
  251. parser: {
  252. dataUrlCondition: {
  253. maxSize: 4 * 1024, // 如果一个模块源码大小小于 maxSize,那么模块会被作为一个 Base64 编码的字符串注入到包中, 否则模块文件会被生成到输出的目标目录中
  254. },
  255. },
  256. },
  257. {
  258. test: /\.(eot|ttf|woff2?)$/,
  259. type: 'asset/resource',
  260. generator: {
  261. filename: 'font/[name]-[contenthash:6][ext]',
  262. },
  263. },
  264. ],
  265. },
  266. plugins: [
  267. // 构建进度条
  268. webpackBarEnable && new WebpackBar(),
  269. // 友好的显示错误信息在终端
  270. new FriendlyErrorsWebpackPlugin(),
  271. // 解析vue
  272. new VueLoaderPlugin(),
  273. // eslint-disable-next-line
  274. ComponentsPlugin({
  275. // eslint-disable-next-line
  276. resolvers: [NaiveUiResolver()],
  277. }),
  278. // windicss
  279. windicssEnable && new WindiCSSWebpackPlugin(),
  280. // 该插件将为您生成一个HTML5文件,其中包含使用脚本标签的所有Webpack捆绑包
  281. new HtmlWebpackPlugin({
  282. filename: 'index.html',
  283. title: htmlWebpackPluginTitle,
  284. template: resolveApp('./public/index.html'),
  285. hash: true,
  286. minify: isProduction
  287. ? {
  288. collapseWhitespace: true, // 折叠空白
  289. keepClosingSlash: true, // 在单标签上保留末尾斜杠
  290. removeComments: true, // 移除注释
  291. removeRedundantAttributes: true, // 移除多余的属性(如:input的type默认就是text,如果写了type="text",就移除它,因为不写它默认也是type="text")
  292. removeScriptTypeAttributes: true, // 删除script标签中type="text/javascript"
  293. removeStyleLinkTypeAttributes: true, // 删除style和link标签中type="text/css"
  294. useShortDoctype: true, // 使用html5的<!doctype html>替换掉之前的html老版本声明方式<!doctype>
  295. // 上面的都是production模式下默认值。
  296. removeEmptyAttributes: true, // 移除一些空属性,如空的id,classs,style等等,但不是空的就全删,比如<img alt />中的alt不会删。http://perfectionkills.com/experimenting-with-html-minifier/#remove_empty_or_blank_attributes
  297. minifyCSS: true, // 使用clean-css插件删除 CSS 中一些无用的空格、注释等。
  298. minifyJS: true, // 使用Terser插件优化
  299. }
  300. : false,
  301. chunks: ['main'], // 要仅包含某些块,您可以限制正在使用的块
  302. }),
  303. // 注入项目信息
  304. new BilldHtmlWebpackPlugin({
  305. env: 'webpack5',
  306. }),
  307. // 将已存在的单个文件或整个目录复制到构建目录。
  308. new CopyWebpackPlugin({
  309. patterns: [
  310. {
  311. from: 'public', // 复制public目录的文件
  312. // to: 'assets', //复制到output.path下的assets,不写默认就是output.path根目录
  313. globOptions: {
  314. ignore: [
  315. // 复制到output.path时,如果output.paht已经存在重复的文件了,会报错:
  316. // ERROR in Conflict: Multiple assets emit different content to the same filename md.html
  317. '**/index.html', // 忽略from目录下的index.html,它是入口文件
  318. ],
  319. },
  320. },
  321. ],
  322. }),
  323. // new EsbuildPlugin({
  324. // target: 'esnext',
  325. // // define: {
  326. // // DSF_FS: JSON.stringify({ d: 23 }),
  327. // // 'process.env.NODE_ENV': JSON.stringify({ d: 32 }),
  328. // // 'process.env.PUBLIC_PATdH': JSON.stringify({ f: 2 }),
  329. // // // 'process.env.VUE_APP_RELEASE_PROJECT_NAME': JSON.stringify(
  330. // // // process.env.VUE_APP_RELEASE_PROJECT_NAME
  331. // // // ),
  332. // // // 'process.env.VUE_APP_RELEASE_PROJECT_ENV': JSON.stringify(
  333. // // // process.env.VUE_APP_RELEASE_PROJECT_ENV
  334. // // // ),
  335. // // // 'process.env.BilldHtmlWebpackPlugin': JSON.stringify(logData()),
  336. // // // 'process.env': {
  337. // // // BilldHtmlWebpackPlugin: JSON.stringify(logData()),
  338. // // // NODE_ENV: JSON.stringify(
  339. // // // isProduction ? 'production' : 'development'
  340. // // // ),
  341. // // // PUBLIC_PATH: JSON.stringify(outputStaticUrl(isProduction)),
  342. // // // VUE_APP_RELEASE_PROJECT_NAME: JSON.stringify(
  343. // // // process.env.VUE_APP_RELEASE_PROJECT_NAME
  344. // // // ),
  345. // // // VUE_APP_RELEASE_PROJECT_ENV: JSON.stringify(
  346. // // // process.env.VUE_APP_RELEASE_PROJECT_ENV
  347. // // // ),
  348. // // // },
  349. // // },
  350. // }),
  351. // 定义全局变量
  352. new DefinePlugin({
  353. BASE_URL: `${JSON.stringify(outputStaticUrl(isProduction))}`, // public下的index.html里面的favicon.ico的路径
  354. 'process.env': {
  355. BilldHtmlWebpackPlugin: JSON.stringify(logData()),
  356. NODE_ENV: JSON.stringify(isProduction ? 'production' : 'development'),
  357. PUBLIC_PATH: JSON.stringify(outputStaticUrl(isProduction)),
  358. VUE_APP_RELEASE_PROJECT_NAME: JSON.stringify(
  359. process.env.VUE_APP_RELEASE_PROJECT_NAME
  360. ),
  361. VUE_APP_RELEASE_PROJECT_ENV: JSON.stringify(
  362. process.env.VUE_APP_RELEASE_PROJECT_ENV
  363. ),
  364. },
  365. __VUE_OPTIONS_API__: false,
  366. __VUE_PROD_DEVTOOLS__: false,
  367. }),
  368. // ts类型检查
  369. // feat: drop support for Vue.js:https://github.com/TypeStrong/fork-ts-checker-webpack-plugin/pull/801
  370. // https://github.com/TypeStrong/fork-ts-checker-webpack-plugin/tree/v6.5.2#vuejs
  371. // fork-ts-checker-webpack-plugin得配合ts-loader使用。
  372. // new ForkTsCheckerWebpackPlugin({
  373. // // https://github.com/TypeStrong/fork-ts-checker-webpack-plugin
  374. // typescript: {
  375. // extensions: {
  376. // vue: {
  377. // enabled: true,
  378. // compiler: resolveApp('./node_modules/vue/compiler-sfc/index.js'),
  379. // },
  380. // },
  381. // diagnosticOptions: {
  382. // semantic: true,
  383. // syntactic: false,
  384. // },
  385. // },
  386. // /**
  387. // * devServer如果设置为false,则不会向 Webpack Dev Server 报告错误。
  388. // * 但是控制台还是会打印错误。
  389. // */
  390. // // devServer: false, // 7.x版本:https://github.com/TypeStrong/fork-ts-checker-webpack-plugin/issues/723
  391. // logger: {
  392. // devServer: false, // fork-ts-checker-webpack-plugin6.x版本
  393. // },
  394. // /**
  395. // * async 为 false,同步的将错误信息反馈给 webpack,如果报错了,webpack 就会编译失败
  396. // * async 默认为 true,异步的将错误信息反馈给 webpack,如果报错了,不影响 webpack 的编译
  397. // */
  398. // async: true,
  399. // }),
  400. // bundle分析
  401. analyzerEnable &&
  402. new BundleAnalyzerPlugin({
  403. analyzerMode: 'server',
  404. generateStatsFile: true,
  405. statsOptions: { source: false },
  406. }), // configuration.plugins should be one of these object { apply, … } | function
  407. // eslint
  408. eslintEnable &&
  409. new ESLintPlugin({
  410. extensions: ['js', 'jsx', 'ts', 'tsx', 'vue'],
  411. emitError: false, // 发现的错误将始终发出,禁用设置为false.
  412. emitWarning: false, // 找到的警告将始终发出,禁用设置为false.
  413. failOnError: false, // 如果有任何错误,将导致模块构建失败,禁用设置为false
  414. failOnWarning: false, // 如果有任何警告,将导致模块构建失败,禁用设置为false
  415. cache: true,
  416. cacheLocation: resolveApp('./node_modules/.cache/.eslintcache'),
  417. }),
  418. ].filter(Boolean),
  419. };
  420. return result;
  421. };
  422. export default (env) => {
  423. return new Promise((resolve) => {
  424. const isProduction = env.production;
  425. process.env.NODE_ENV = isProduction ? 'production' : 'development';
  426. const configPromise = Promise.resolve(
  427. isProduction ? prodConfig : devConfig
  428. );
  429. configPromise.then(
  430. (config: any) => {
  431. // 根据当前环境,合并配置文件
  432. const mergeConfig = merge(commonConfig(isProduction), config);
  433. console.log(
  434. chalkWARN(
  435. `根据当前环境,合并配置文件,当前是: ${process.env.NODE_ENV!}环境`
  436. )
  437. );
  438. resolve(mergeConfig);
  439. },
  440. (err) => {
  441. console.log(err);
  442. }
  443. );
  444. });
  445. };