@mega-apps/cli
Version:
Mom builder for all mega modules apps. The recommended basic operation dependency package is attached, and users can check and repair defects in actual applications.
811 lines (724 loc) • 29.5 kB
JavaScript
const path = require("path");
const fs = require("fs");
// 当前运行目录
const cwd = process.cwd();
/**
* 定义启用配置
* @param enable
* @param currentValue
* @param restValue
* @return {*}
*/
export const def = (enable = 1, currentValue, restValue) => {
const defaultValueMap = {
Object: {},
Array: [],
Function: () => {
},
};
let defaultValue;
try {
defaultValue =
restValue === undefined
? defaultValueMap[currentValue.constructor.name]
: restValue;
} catch (error) {
}
return [1, true].includes(enable) ? currentValue : defaultValue;
};
/**
* 过滤存在的文件
* @param files
* @return {*[]}
*/
export const filterOnlyExistFiles = (files = []) => {
return files
.map((filePath) => {
return {
filePath,
exists: fs.existsSync(filePath),
};
})
.filter((cfg) => cfg.exists)
.map(({filePath}) => filePath);
};
/**
* 获得内置的配置文件
* @param relativeFiles
* @return {*[]}
*/
export const getConfigFiles = (relativeFiles = [], workDir = __dirname) => {
return filterOnlyExistFiles(
relativeFiles
.map((file) => [file, `../config/${file}`])
.flat()
.map((file) => path.join(workDir, file))
);
};
/**
* stylelint 规则文件数组
* @type {*[]}
*/
export const stylelintRcFileIds = [
".stylelintrc",
".stylelintrc.json",
".stylelintrc.yaml",
".stylelintrc.yml",
".stylelintrc.js",
"stylelint.config.js",
]
export const stylelintrcFiles = getConfigFiles(stylelintRcFileIds);
export const currentWorkDirStylelintrcFiles = getConfigFiles(stylelintRcFileIds, cwd);
/**
* eslint 规则文件数组
* @type {*[]}
*/
export const eslintRcFileIds = [
".eslintrc",
".eslintrc.json",
".eslintrc.yaml",
".eslintrc.yml",
".eslintrc.js",
];
export const eslintrcFiles = getConfigFiles(eslintRcFileIds);
export const currentWorkDirEslintrcFiles = getConfigFiles(eslintRcFileIds, cwd);
/**
* tsconfig 规则文件数组
* @type {*[]}
*/
export const tsconfigFileIds = [
"tsconfig.json"
];
export const tsconfigFiles = getConfigFiles(tsconfigFileIds);
export const currentWorkDirTsconfigFiles = getConfigFiles(tsconfigFileIds, cwd);
/**
* 获得默认的Sass解析器
* @param defaultPkg, 默认值:node-sass, 可选值:sass
* @returns module.exports
* @note 关于node-sass的版本要根据nodejs的版本指定,参见:https://www.npmjs.com/package/node-sass 内的版本号对应说明
*/
export const getDefaultSassImplementation = (defaultPkg = "node-sass") => {
let sassImplPkg = defaultPkg;
try {
require.resolve(sassImplPkg);
} catch (error) {
try {
require.resolve("node-sass");
sassImplPkg = "node-sass";
} catch (ignoreError) {
sassImplPkg = "sass";
}
} // eslint-disable-next-line import/no-dynamic-require, global-require
return require(sassImplPkg);
}
/**
* 获得Fix的Module Name
* @param moduleName
* @return {string|*}
*/
export const loadFixModuleName = (moduleName) => {
try {
const pkg = path.join(__dirname, "../node_modules", moduleName);
require.resolve(pkg);
return pkg;
} catch (e) {
}
return moduleName;
}
/**
* 获得完全适配 PostCss V8 的 postcss-preset-env 插件版本
*/
export const getPostCssPresetEnvPluginPathForPostcssV8 = () => {
// FIXME 如果默认的 postcss-preset-env 版本,并不能解决问题, 请直接使用完全路径的 postcss-preset-env 进行替换
// 例如:通过 require.resolve() 函数获得
// eg. require.resolve(path.join(__dirname,"../node_modules","postcss-preset-env"))
return loadFixModuleName("postcss-preset-env");
}
/**
* 获得 PurgeCss Plugin
* @return {string|*}
*/
export const getPurgeCssPlugin = () => loadFixModuleName("@fullhuman/postcss-purgecss");
export const isProductEnv = process?.env?.NODE_ENV === "production";
export const isDevEnv = process?.env?.NODE_ENV === "development";
/**
* 生成基础的nuxt配置
* @param supportIE
* @param supportPWA
* @param supportSEO
* @param supportESLint
* @param supportStyleLint
* @param supportTypeScript
* @param supportTailwindCSS
* @param supportImageOptimized
* @param supportSvgSuperLoad
* @param supportSvgSprite
* @param supportDateIntegrationWithMoment
* @param supportDateIntegrationWithDateJS
* @param supportDateIntegrationWithDateFns
* @param supportSocketIO
* @param supportDeviceDetect
* @param supportCloudinary
* @param supportUniversalStorageUtilities
* @param supportHtmlValidator
* @param supportWebVitalsByGoogle
* @param supportSpeedKit
* @param supportNuxtCustomElements
* @param forceUsePostCssV8 强制使用PostCss Ver 8 版本,关联的 postcss-preset-env 也使用兼容 V8 的最高版本
* @param preventBuildTranspileDefaultSet 阻止默认的Build.transpile设置
* @param preventBuildOptimizationDefaultSet 阻止默认的Build.optimization设置
* @param enablePurgeCss
* @param preventUseNuxtAxiosModule 阻止默认使用 @nuxtjs/axios 模块
* @param preventUseNuxtAuthModule 阻止模式使用 @nuxtjs/auth 模块
* @return nuxt.config content
*/
export const generateBaseConfig = ({
supportIE = false,
supportPWA = false,
supportSEO = false,
supportESLint = false,
supportStyleLint = false,
supportTypeScript = false,
supportTailwindCSS = false,
supportImageOptimized = false,
supportSvgSuperLoad = false,
supportSvgSprite = false,
supportDateIntegrationWithMoment = false,
supportDateIntegrationWithDateJS = false,
supportDateIntegrationWithDateFns = false,
supportSocketIO = false,
supportDeviceDetect = false,
supportCloudinary = false,
supportUniversalStorageUtilities = false,
supportHtmlValidator = false,
supportWebVitalsByGoogle = false,
supportSpeedKit = false,
supportNuxtCustomElements = false,
forceUsePostCssV8 = false,
preventBuildTranspileDefaultSet = false,
preventBuildOptimizationDefaultSet = false,
enablePurgeCss = false,
preventUseNuxtAxiosModule = false,
preventUseNuxtAuthModule = false,
}) => {
return {
/**
* https://nuxtjs.org/docs/2.x/get-started/upgrading
* If you are upgrading to Nuxt v2.14 and want to use static hosting then you will need to
* add target:static to your nuxt.config.js file in order for the generate command to work properly.
*/
target: "static",
ssr: false,
telemetry: false,
// Global page headers: https://go.nuxtjs.dev/config-head
head: {
meta: [
{charset: "utf-8"},
{name: "viewport", content: "width=device-width, initial-scale=1"},
{hid: "description", name: "description", content: ""},
],
link: [{rel: "icon", type: "image/x-icon", href: "/favicon.ico"}],
/* IE需要添加proxy-polyfill */
...def(supportIE, {script: [{src: "/js/es6-proxy-polyfill.js"}]}),
},
// Global CSS: https://go.nuxtjs.dev/config-css
css: [
// TODO: 单独使用antd的时候需要验证是否可以真正通过省略使用antd的css文件, 条件:ant-design-vue 样式通过less的方式导出
// Note: 验证不需要特别指定,默认使用less,可以正常输出样式
...def(0, ["@mega-design/ui-vue/dist/mega-design.css"]),
...def(0, ["ant-design-vue/dist/antd.css"]),
...[],
],
// Plugins to run before rendering page: https://go.nuxtjs.dev/config-plugins
// 插件自上而下顺序执行。数组元素的次序
plugins: [...[]],
// Auto import components: https://go.nuxtjs.dev/config-components
components: true,
// Modules for dev and build (recommended): https://go.nuxtjs.dev/config-modules
buildModules: [
/* 开启 Mom Modules 功能*/
// Mom提供的注入Nuxt的模块
...def(1, ["@mega-apps/nuxt-plugin-mom"]),
/* 使用自己的eslint */
// https://go.nuxtjs.dev/eslint
...def(supportESLint, ["@mega-apps/nuxt-module-eslint-mom"]),
/* 使用自己的stylelint */
// https://go.nuxtjs.dev/stylelint
...def(supportStyleLint, ["@mega-apps/nuxt-module-stylelint-mom"]),
/* 使用Postcss8 作为编译器 */
...def(forceUsePostCssV8, ["@nuxt/postcss8"]),
/* 支持typescript 编译*/
// https://go.nuxtjs.dev/typescript
...def(supportTypeScript, [["@nuxt/typescript-build", {typeCheck: false}]]),
/* 开启日期时间函数库集成 */
...def(supportDateIntegrationWithMoment, ["@nuxtjs/moment"]),
...def(supportDateIntegrationWithDateFns, ["@nuxtjs/date-fns"]),
/* 开启支持socket-io集成 */
...def(supportSocketIO, ["nuxt-socket-io"]),
/* 开启设备检测库集成 */
...def(supportDeviceDetect, ["@nuxtjs/device"]),
/* 开启HTML代码规则检测 */
...def(supportHtmlValidator, ["@nuxtjs/html-validator"]),
/* 开启Google Web Vitals*/
...def(supportWebVitalsByGoogle, ["@nuxtjs/web-vitals"]),
/* 支持图片优化 */
// https://image.nuxtjs.org/
// https://github.com/nuxt-community/imagemin-module
...def(supportImageOptimized, ["@nuxt/image", "@nuxtjs/imagemin"]),
/* 支持Tailwind CSS */
// https://go.nuxtjs.dev/tailwindcss
...def(supportTailwindCSS, ["@nuxtjs/tailwindcss"]),
//nuxt-webpack-optimisations
// NOTE: nuxt-webpack-optimisations v2.2.3 优化的效果,当前还没有我们内置的配置最终产物性能高
...def(0, ["nuxt-webpack-optimisations "]),
/* 其他,占位 */
...[],
],
// Modules: https://go.nuxtjs.dev/config-modules
modules: [
/* 开启axios */
// https://go.nuxtjs.dev/axios
...def(!preventUseNuxtAxiosModule, ["@nuxtjs/axios"]),
/* 开启auth */
// https://go.nuxtjs.dev/auth
...def(!preventUseNuxtAuthModule, ["@nuxtjs/auth"]),
/* 开启pwa */
// https://go.nuxtjs.dev/pwa
...def(supportPWA, ["@nuxtjs/pwa"]),
/* 开启日期时间函数库集成 */
...def(supportDateIntegrationWithDateJS, ["@nuxtjs/dayjs"]),
/* 开启支持Cloudinary */
...def(supportCloudinary, ["@nuxtjs/cloudinary"]),
/* 开启支持加载svg图片外挂*/
...def(supportSvgSuperLoad, ["@nuxtjs/svg"]),
/* 开启支持SVG 精灵外挂 */
...def(supportSvgSprite, ["@nuxtjs/svg-sprite"]),
/* 开启通用存储工具 */
// https://github.com/nuxt-community/universal-storage-module
...def(supportUniversalStorageUtilities, ["@nuxtjs/universal-storage"]),
/* 开启SEO优化 */
...def(supportSEO, [
"@nuxtjs/redirect-module",
"@nuxtjs/robots",
"@nuxtjs/sitemap",
]),
/* 开启支持 SpeedKit */
// https://nuxt-speedkit.grabarzundpartner.dev/
...def(supportSpeedKit, ["nuxt-speedkit"]),
/* 开启支持 Nuxt Custom Elements */
// https://nuxt-custom-elements.grabarzundpartner.dev/setup
...def(supportNuxtCustomElements, ["nuxt-custom-elements"]),
/* 开启Pre Compress */
/* 默认开启压缩 gzip 生产环境*/
...def(isProductEnv, ["nuxt-precompress"]),
...[],
],
// @mega-apps/nuxt-plugin-mom module configuration
momModules: [...[]],
/**
* ESLint 设置
* eslint module configuration: https://www.npmjs.com/package/@nuxtjs/eslint-module
* https://eslint.org/docs/developer-guide/nodejs-api#-new-eslintoptions
*/
...def(supportESLint, {
eslint: {
/* 内部指定规则配置文件,为Mom统一设置样式规则 default:null */
...def(
// (currentWorkDirEslintrcFiles.length < 1) &&
(eslintrcFiles.length > 0), {
overrideConfigFile: eslintrcFiles[0],
}),
},
}),
// stylelint module configuration:https://www.npmjs.com/package/@nuxtjs/stylelint-module
// http://stylelint.io/user-guide/node-api/#options
...def(supportStyleLint, {
stylelint: {
/* 内部指定规则配置文件,为Mom统一设置样式规则 default:null */
...def(
// (currentWorkDirStylelintrcFiles.length < 1) &&
(stylelintrcFiles.length > 0), {
configFile: stylelintrcFiles[0],
}),
},
}),
// 支持Typescript编译
// typescript-build module configuration:https://github.com/nuxt/typescript/blob/master/packages/typescript-build/src/index.ts
...def(supportTypeScript, {
typescript: {
ignoreNotFoundWarnings: true,
typeCheck: {
// 覆盖关于typeCheck的处理
typescript: {
...def(
// (currentWorkDirTsconfigFiles.length < 1) &&
(tsconfigFiles.length > 0), {
configFile: tsconfigFiles[0]
}),
},
},
...def(
// (currentWorkDirTsconfigFiles.length < 1) &&
(tsconfigFiles.length > 0), {
configFile: tsconfigFiles[0]
}),
},
}),
...def(supportSocketIO, {
io: {},
}),
/* 默认开启压缩 gzip 生产环境*/
...def(isProductEnv, {
nuxtPrecompress: {
enabled: true, // Enable in production
report: false, // set true to turn one console messages during module init
test: /\.(js|css|html|txt|xml|json|svg|xls|xlsx|jpg|jpeg|png|webp|gif|icon|ttf|eot|woff|woff2|mp3|mp4)$/, // files to compress on build
// Serving options
middleware: {
// You can disable middleware if you serve static files using nginx...
enabled: true,
// Enable if you have .gz or .br files in /static/ folder
enabledStatic: true, // 测试无效
// Priority of content-encodings, first matched with request Accept-Encoding will me served
encodingsPriority: ['br', 'gzip'],
},
// build time compression settings
gzip: {
threshold: 8192,
minRatio: 0.8,
compressionOptions: {level: 9},
},
brotli: {
compressionOptions: {level: 11},
threshold: 8192,
minRatio: 0.8,
},
},
}),
/* 开启支持 SpeedKit的默认配置 */
// 帮助文档:https://nuxt-speedkit.grabarzundpartner.dev/options
...def(supportSpeedKit, {
speedkit: {
detection: {
performance: true,
browserSupport: true
},
performanceMetrics: {
device: {
hardwareConcurrency: {min: 2, max: 48},
deviceMemory: {min: 2}
},
timing: {
fcp: 800,
dcl: 1200
},
lighthouseDetectionByUserAgent: false
},
},
}),
/* 开启支持 Nuxt Custom Elements的默认配置 */
// 帮助文档:https://nuxt-custom-elements.grabarzundpartner.dev/options
...def(supportNuxtCustomElements, {
customElements: {}
}),
// Axios module configuration: https://go.nuxtjs.dev/config-axios
...def(!preventUseNuxtAxiosModule, {
/**
* 网络请求设置
*/
axios: {
proxy: true,
},
/**
* 网络代理表设置
*/
proxy: {},
}),
// PWA module configuration: https://go.nuxtjs.dev/pwa
...def(supportPWA, {
pwa: {
manifest: {
lang: "en",
},
},
}),
// Render Configuration: https://nuxtjs.org/docs/configuration-glossary/configuration-render
render: {
bundleRenderer: {
shouldPreload: (file, type) => {
return ["script", "style", "font"].includes(type)
},
},
resourceHints: true,
csp: true,
http2: {
push: true
},
static: {
maxAge: '1y'
}
},
// Build Configuration: https://nuxtjs.org/docs/configuration-glossary/configuration-build
build: {
/**
* Babel 扩展设置
*/
babel: {
/**
* 解决:[BABEL] Note: The code generator has deoptimised the styling of XXX.js as it exceeds the max of 500KB.
*/
compact: false,
/**
* IE需要添加core-js 2的版本
* @note 参照:https://github.com/nuxt/nuxt.js/tree/dev/packages/babel-preset-app
*/
...def(supportIE, {
presets({envName}) {
const envTargets = {
client: {browsers: ["last 2 versions"], ie: 8},
server: {node: "current"},
};
console.warn(
"You must install core-js@^2 for support IE browser runtime"
);
return [
[
"@nuxt/babel-preset-app",
{
forceAllTransforms: true,
modules: false,
targets: {ie: "8"},
corejs: {version: 2},
},
],
];
},
}),
/**
* 插件配置
*/
plugins: [
/**
* 解决组件引入
*/
...[
[
"babel-plugin-import", // 7.x 版本写法,如果是6.x版本应为:"import"
{
libraryName: "ant-design-vue",
libraryDirectory: "es",
style: true, // 强制使用less
},
"ant-design-vue", // 可以直接使用 ant-design-vue 组件
],
[
"babel-plugin-import",
{
libraryName: "@mega-design/ui-vue",
libraryDirectory: "es",
style: true, // 强制使用less
},
"@mega-design/ui-vue", // 组件库扩展功能
],
],
/**
* 解决Nuxt自身升级2.15.4 -> 2.15.5 导致的宽泛的依赖包引发的升级导致
* Though the "loose" option was set to "false" in your @babel/preset-env config,
* it will not be used for @babel/plugin-proposal-private-methods since the "loose" mode option was set to "true" for @babel/plugin-proposal-class-properties.
The "loose" option must be the same for @babel/plugin-proposal-class-properties, @babel/plugin-proposal-private-methods and @babel/plugin-proposal-private-property-in-object (when they are enabled): you can silence this warning by explicitly adding
["@babel/plugin-proposal-private-methods", { "loose": true }]
to the "plugins" section of your Babel config.
*/
["@babel/plugin-proposal-class-properties", {loose: true}],
["@babel/plugin-proposal-private-methods", {loose: true}],
["@babel/plugin-proposal-private-property-in-object", {loose: true}],
],
/**
* 关于 preset的配置,参见:https://github.com/nuxt/nuxt.js/tree/dev/packages/babel-preset-app
*/
},
/**
* 透传编译
*
* 涉及的问题1: [webpack vendor library not converted to ES5](https://stackoverflow.com/questions/67052911/webpack-vendor-library-not-converted-to-es5)
*
* 将 node_modules下的包作为源码引入. 相当于是项目工程源码的一部分
*
* 影响:相当于项目源码文件数量增加,会降低编译构建速度
* 适用于:如 ant-design-vue,@mega-design 中的less统一编译,有助于less变量值的替换
*
* 用途:也是用来解决引用的包是ES6的,没有转移成ES5的问题。针对IE11
*
*
* 1. Build Configuration: `nuxt.js-2.15.2\packages\config\src\config\build.js`
*/
...def(!preventBuildTranspileDefaultSet, {
transpile: [
/**
* 以下库采用的都是es模块,或者ES6的语法,需要作为源码一部分,来解决ES6转换成ES5的问题
*/
...def(supportIE, [/@mega-design/, /@mega-apps\/utils/, /ant-design-vue/]),
/**
* 查找源码中,引用了element-ui库的代码部分,参与编译
* 错误示例:
* 1. `/^element-ui/ `: 无法匹配到非规范模式。 应该使用 /element-ui/
*
* 已知的问题:
* (1)`element-ui.common.js` 是已经编译过的,过大,会受到Babel编译的错误警告
*/
...def(supportIE, [/element-ui/]),
],
}),
/**
* 对loader的特殊设置
*
*
* 1. Build Configuration: `nuxt.js-2.15.2\packages\config\src\config\build.js` about loaders
*/
loaders: {
vue: {
/* 开启导出组件名称自动命名功能,文件名称默认作为组件的名称, 主要用途:用于KeepAlive组件未定义名称自动处理生产包处理 */
exposeFilename: true,
/* 使用 vue-template-babel-compiler 编译Vue模板*/
compiler: require(loadFixModuleName("vue-template-babel-compiler")),
},
less: {
lessOptions: {
/* 修改变量 */
modifyVars: {},
/* 支持JS */
javascriptEnabled: true,
},
},
// #region 针对sass/scss的解析默认配置
sass: {
implementation: getDefaultSassImplementation()
},
scss: {
implementation: getDefaultSassImplementation()
}
// #endregion
},
/**
* 对css优化, 方便CSS preload 及优化拆分.
* https://nuxtjs.org/docs/configuration-glossary/configuration-build#extractcss
*/
extractCSS: true,
// 只对生产环境有影响
...def(isProductEnv, {
optimizeCSS: true, // 优化CSS
}),
/**
* 针对PostCss的特殊设置
*/
...def(forceUsePostCssV8, {
postcss: {
plugins: {
// 由于官方 @nuxt/postcss8 并没有完全解决全部使用 postcss v8 的问题,因此,以下指定的插件必须要从队列中去除
// 原因:加载的如下插件,还是被指定成 7.x 系列版本
// 解决方法1: 对应key值为 false,表示让Nuxt过滤掉这些插件,该操作,不会影响其他新的插件的加入
// 解决方法2: 以下插件,明确修正成适应 V8 的版本
"postcss-custom-properties": false,
"postcss-nesting": false,
"cssnano": false,
/* 强制使用cli 提供的 postcss-preset-env 版本 */
[getPostCssPresetEnvPluginPathForPostcssV8()]: {},
/* 检测postcss-purgecss是否存在, 只影响生产环境: 有些项目不适合去除无用的css, !!谨慎使用!! */
// 已知:oasis-sass-vue. mom1 - mom2 nuva 都不适用该特性
...def(isProductEnv && enablePurgeCss, {
[getPurgeCssPlugin()]: {
content: ['./pages/**/*.vue', './views/**/*.vue', './layouts/**/*.vue', './components/**/*.vue'],
safelist: ['html', 'body'],
},
}),
},
},
}),
/**
* 【谨记】开启后,有异常,不稳定。 cache用于提升构建性能
* 如果cache=true发现不稳定,可在外部nuxt.config.js 中禁止掉
*/
cache: false, // cache 不稳定,这里不强制设置,默认关闭
/**
* 【谨记】生产环境,由于公司的Jenkins使用主机打包,会占用100%cpu,所以生产环境不开启;
* 需要开启,请在外部扩展的配置中,赋值为 parallel: true
* 默认强制关闭
*/
parallel: false,
/**
* 优化构建产物、数据块的大小
*
*
* 1. Build Configuration: `nuxt.js-2.15.2\packages\config\src\config\build.js` about optimization
*/
...def(!preventBuildOptimizationDefaultSet, {
terser: {
terserOptions: {
// https://github.com/terser/terser#compress-options
compress: {
pure_funcs: ["console.log", "console.debug", "console.warn"],
},
},
},
optimization: {
splitChunks: {
// 调整最大的maxSize,可根据实际项目,自己再优化配置
maxSize: 1.1111 * 1024 * 10 * 1000, // 摩尔数,
/**
* 优化策略:
* 固定场景下,减少包的体积大小,优化性能面临两个关键因素的影响:分包策略与网络请求策略;(分包策略与网络请求策略既冲突,又统一)
* 但是,要避免以下几种情况:
* 1. 不管什么都分包,这会增加网络请求数量,也会导致性能会下降
* 2. 分包的大小过大,也会导致性能下降
* 3. 分包的优先级会影响加载前后关系。"priority" 级别越高,越先放到页面中
* 分包与减少网络请求时互斥的。所以,要分析哪些包需要分包,哪些不需要分包。结合网络请求数量,找到性能平衡点。
* 其实优化就是一个博弈的过程。需要根据实际情况,多测试,多验证。
* 参考文章:
* - https://blog.benjames.io/2020/06/12/nuxt-performance/
* - https://www.cnblogs.com/chris-oil/p/13941815.html
* - https://zhuanlan.zhihu.com/p/66212099
* - https://zhuanlan.zhihu.com/p/66212922
*/
cacheGroups: {
// UI组件库,属于高频更新库,单独分包
"base-ui": {
test: (module) => (/node_modules[\\/](ant-design-vue|@antd|@ant-design|element-ui)/.test(module.context)),
name: "base-ui",
chunks: "all",
priority: 20,
},
"mega-design": {
test: (module) => (/node_modules[\\/](@mega-design[\\/])/.test(module.context)),
name: "mega-design",
chunks: "all",
priority: 12,
},
/**
* 自定义组件/函数 chunk-commons部分
* 分包策略:
* 这部分主要分为两部分:(1)必要; (2)可选
* 1. 必要:是指那些项目里必须加载它们才能正常运行的组件或者函数。比如你的路由表、全局 state、全局侧边栏/Header/Footer 等组件、自定义 Svg 图标等等。这些其实就是你在入口文件中依赖的东西,它们都会默认打包到bundle中。
* 2. 可选:是指被大部分页面使用,但在入口文件 entry 中未被引入的模块。比如:一个管理后台,你封装了很多 select 或者 table 组件,由于它们的体积不会很大,它们都会被默认打包到到每一个懒加载页面的 chunk 中,这样会造成不少的浪费。你有十个页面引用了它,就会包重复打包十次。所以应该将那些被大量共用的组件单独打包成chunk-commons。不过还是要结合具体情况来看。一般情况下,你也可以将那些非必要组件\函数也在入口文件 entry 中引入,和必要组件\函数一同打包到bundle之中也是没什么问题的
* 【特别说明】:有一类叫低频组件,很容易被混淆到commons中,它与chunk-commons 最大的区别是,它们只会在一些特定业务场景下使用,比如富文本编辑器、js-xlsx前端 excel 处理库等。一般这些库都是第三方的且大于 30kb,所以 webpack 4 会默认打包成一个独立的 bundle。也无需特别处理。小于 30kb 的情况下会被打包到具体使用它的页面 bundle 中
*/
commons: {
test: /node_modules[\\/](vue|vue-loader|vue-router|vuex|vue-meta|core-js|@babel\/runtime|axios|webpack|setimmediate|timers-browserify|process|regenerator-runtime|cookie|js-cookie|is-buffer|dotprop|url-polyfill|@nuxt[\\/]ufo|ufo|nuxt\.js)[\\/]/,
name: true,
priority: 10
},
},
},
},
}),
},
};
};
/**
* 导出默认Nuxt.config.js配置
*/
export default generateBaseConfig({
supportTailwindCSS: true,
supportESLint: true,
supportStyleLint: true,
supportTypeScript: true,
});