webpack.common.ts 16 KB

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