env.js 13.8 KB
Newer Older
fxy060608's avatar
fxy060608 已提交
1
const fs = require('fs')
fxy060608's avatar
fxy060608 已提交
2
const path = require('path')
fxy060608's avatar
fxy060608 已提交
3
const mkdirp = require('mkdirp')
4
const loaderUtils = require('loader-utils')
fxy060608's avatar
fxy060608 已提交
5

fxy060608's avatar
fxy060608 已提交
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
const defaultInputDir = 'src'
if (process.env.UNI_INPUT_DIR && process.env.UNI_INPUT_DIR.indexOf('./') === 0) {
  process.env.UNI_INPUT_DIR = path.resolve(process.cwd(), process.env.UNI_INPUT_DIR)
}
process.env.UNI_INPUT_DIR = process.env.UNI_INPUT_DIR || path.resolve(process.cwd(), defaultInputDir)

// 初始化全局插件对象
global.uniPlugin = require('@dcloudio/uni-cli-shared/lib/plugin').init()
console.log('debug:::', global.uniPlugin)
const manifestJsonObj = require('@dcloudio/uni-cli-shared/lib/manifest').getManifestJson()
const platformOptions = manifestJsonObj[process.env.UNI_SUB_PLATFORM || process.env.UNI_PLATFORM] || {}
// 插件校验环境
global.uniPlugin.validate.forEach(validate => {
  validate(platformOptions, manifestJsonObj)
})

process.UNI_MANIFEST = manifestJsonObj

雪洛's avatar
雪洛 已提交
24
process.UNI_CLOUD = false
25
process.UNI_CLOUD_TCB = false
fxy060608's avatar
fxy060608 已提交
26
process.UNI_CLOUD_ALIYUN = false
27
process.env.UNI_CLOUD_PROVIDER = JSON.stringify([])
fxy060608's avatar
fxy060608 已提交
28 29 30 31

if (process.env.UNI_CLOUD_SPACES) {
  try {
    const spaces = JSON.parse(process.env.UNI_CLOUD_SPACES)
fxy060608's avatar
fxy060608 已提交
32
    if (Array.isArray(spaces)) {
雪洛's avatar
雪洛 已提交
33
      process.UNI_CLOUD = spaces.length > 0
34
      process.UNI_CLOUD_TCB = !!spaces.find(space => !space.clientSecret)
fxy060608's avatar
fxy060608 已提交
35 36
      process.UNI_CLOUD_ALIYUN = !!spaces.find(space => space.clientSecret)
      if (spaces.length === 1) {
fxy060608's avatar
fxy060608 已提交
37
        const space = spaces[0]
38
        console.log(`本项目的uniCloud使用的默认服务空间spaceId为:${space.id}`)
fxy060608's avatar
fxy060608 已提交
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
      }
      process.env.UNI_CLOUD_PROVIDER = JSON.stringify(spaces.map(space => {
        if (space.clientSecret) {
          return {
            provider: 'aliyun',
            spaceName: space.name,
            spaceId: space.id,
            clientSecret: space.clientSecret,
            endpoint: space.apiEndpoint
          }
        } else {
          return {
            provider: 'tencent',
            spaceName: space.name,
            spaceId: space.id
          }
        }
56
      }))
fxy060608's avatar
fxy060608 已提交
57 58
    }
  } catch (e) {}
fxy060608's avatar
fxy060608 已提交
59
}
fxy060608's avatar
fxy060608 已提交
60

fxy060608's avatar
fxy060608 已提交
61
if (
雪洛's avatar
雪洛 已提交
62
  process.UNI_CLOUD &&
fxy060608's avatar
fxy060608 已提交
63 64 65
  process.env.UNI_PLATFORM === 'h5' &&
  process.env.NODE_ENV === 'production'
) {
雪洛's avatar
雪洛 已提交
66
  console.warn(`发布H5,需要在uniCloud后台操作,绑定安全域名,否则会因为跨域问题而无法访问。教程参考:https://uniapp.dcloud.io/uniCloud/quickstart-H5`)
fxy060608's avatar
fxy060608 已提交
67 68
}

fxy060608's avatar
fxy060608 已提交
69 70 71
// 初始化环境变量
const defaultOutputDir = '../../../../dist/' +
  (process.env.NODE_ENV === 'production' ? 'build' : 'dev') + '/' +
fxy060608's avatar
fxy060608 已提交
72
  (process.env.UNI_SUB_PLATFORM || process.env.UNI_PLATFORM)
fxy060608's avatar
fxy060608 已提交
73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89

if (process.env.UNI_OUTPUT_DIR && process.env.UNI_OUTPUT_DIR.indexOf('./') === 0) {
  process.env.UNI_OUTPUT_DIR = path.resolve(process.cwd(), process.env.UNI_OUTPUT_DIR)
}

process.env.UNI_PLATFORM = process.env.UNI_PLATFORM || 'h5'
process.env.VUE_APP_PLATFORM = process.env.UNI_PLATFORM
process.env.UNI_OUTPUT_DIR = process.env.UNI_OUTPUT_DIR || path.resolve(__dirname, defaultOutputDir)

if (process.env.UNI_PLATFORM === 'app-plus') {
  process.env.UNI_OUTPUT_TMP_DIR = path.resolve(process.env.UNI_OUTPUT_DIR, '../.tmp/app-plus')
}

process.env.UNI_CLI_CONTEXT = path.resolve(__dirname, '../../../../')

process.UNI_LIBRARIES = process.UNI_LIBRARIES || ['@dcloudio/uni-ui']

fxy060608's avatar
fxy060608 已提交
90
if (process.env.NODE_ENV === 'production') { // 发行模式,不启用 cache
91
  delete process.env.UNI_USING_CACHE
fxy060608's avatar
fxy060608 已提交
92 93
}

fxy060608's avatar
fxy060608 已提交
94
const {
fxy060608's avatar
fxy060608 已提交
95
  normalizePath,
fxy060608's avatar
fxy060608 已提交
96 97
  isSupportSubPackages,
  runByHBuilderX,
fxy060608's avatar
fxy060608 已提交
98
  getPagesJson
fxy060608's avatar
fxy060608 已提交
99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120
} = require('@dcloudio/uni-cli-shared')

const pagesJsonObj = getPagesJson()
// 读取分包
process.UNI_SUBPACKAGES = {}
if (Array.isArray(pagesJsonObj.subPackages)) {
  pagesJsonObj.subPackages.forEach(subPackage => {
    if (subPackage && subPackage.root) {
      const {
        name,
        root,
        independent
      } = subPackage
      process.UNI_SUBPACKAGES[root] = {
        name,
        root,
        independent
      }
    }
  })
}

fxy060608's avatar
fxy060608 已提交
121 122
process.UNI_PAGES = pagesJsonObj

fxy060608's avatar
fxy060608 已提交
123 124 125 126 127 128 129 130
if (manifestJsonObj.debug) {
  process.env.VUE_APP_DEBUG = true
}

process.UNI_STAT_CONFIG = {
  appid: manifestJsonObj.appid
}

131 132
// 默认启用 自定义组件模式
// if (isInHBuilderXAlpha) {
133
let usingComponentsAbsent = false
134
if (!platformOptions.hasOwnProperty('usingComponents')) {
135
  usingComponentsAbsent = true
136
}
fxy060608's avatar
fxy060608 已提交
137
platformOptions.usingComponents = true
138
// }
fxy060608's avatar
fxy060608 已提交
139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168

if (process.env.UNI_PLATFORM === 'h5') {
  const optimization = platformOptions.optimization
  if (optimization) {
    // 发行模式且主动启用优化
    const treeShaking = optimization.treeShaking
    if (
      treeShaking &&
      treeShaking.enable &&
      process.env.NODE_ENV === 'production'
    ) {
      process.env.UNI_OPT_TREESHAKINGNG = true
      process.UNI_USER_APIS = new Set()
      if (Array.isArray(treeShaking.modules) && treeShaking.modules.length) {
        const {
          parseUserApis
        } = require('@dcloudio/uni-cli-shared/lib/api')
        try {
          const modules = require('@dcloudio/uni-h5/lib/modules.json')
          process.UNI_USER_APIS = parseUserApis(treeShaking.modules || [], modules)
        } catch (e) {}
      }
    }
    if (optimization.prefetch) {
      process.env.UNI_OPT_PREFETCH = true
    }
    if (optimization.preload) {
      process.env.UNI_OPT_PRELOAD = true
    }
  }
169 170
  const buffer = fs.readFileSync(require.resolve('@dcloudio/uni-h5/dist/index.css'))
  process.env.VUE_APP_INDEX_CSS_HASH = loaderUtils.getHashDigest(buffer, 'md5', 'hex', 8)
fxy060608's avatar
fxy060608 已提交
171 172 173 174 175 176
}

if (process.env.UNI_PLATFORM === 'mp-qq') { // QQ小程序 强制自定义组件模式
  platformOptions.usingComponents = true
}

177
let isNVueCompiler = true
fxy060608's avatar
fxy060608 已提交
178
if (process.env.UNI_PLATFORM === 'app-plus') {
179 180
  if (platformOptions.nvueCompiler === 'weex') {
    isNVueCompiler = false
fxy060608's avatar
fxy060608 已提交
181
  }
fxy060608's avatar
fxy060608 已提交
182 183 184
  if (
    platformOptions.compilerVersion === '3' ||
    platformOptions.compilerVersion === 3
fxy060608's avatar
fxy060608 已提交
185
  ) {
fxy060608's avatar
fxy060608 已提交
186
    delete process.env.UNI_USING_CACHE
fxy060608's avatar
fxy060608 已提交
187
    if (platformOptions.renderer === 'native') {
fxy060608's avatar
fxy060608 已提交
188
      process.env.UNI_USING_V3_NATIVE = true
fxy060608's avatar
fxy060608 已提交
189 190 191 192
    } else {
      process.env.UNI_USING_V3 = true
      platformOptions.usingComponents = true
    }
Q
qiang 已提交
193
    process.env.UNI_OUTPUT_TMP_DIR = ''
194
    isNVueCompiler = true // v3 目前仅支持 uni-app 模式
fxy060608's avatar
fxy060608 已提交
195
  } else if (platformOptions.renderer === 'native') {
fxy060608's avatar
fxy060608 已提交
196
    // 纯原生目前不提供 cache
197
    delete process.env.UNI_USING_CACHE
fxy060608's avatar
fxy060608 已提交
198 199 200 201
    process.env.UNI_USING_NATIVE = true
    process.env.UNI_USING_V8 = true
    process.env.UNI_OUTPUT_TMP_DIR = ''
  }
fxy060608's avatar
fxy060608 已提交
202 203 204 205 206 207 208 209 210 211 212 213 214 215
  // v3 支持指定 js 混淆(仅发行模式)
  if (
    process.env.NODE_ENV === 'production' &&
    process.env.UNI_USING_V3
  ) {
    const resources = platformOptions.confusion &&
      platformOptions.confusion.resources
    const resourcesKeys = resources &&
      Object.keys(resources).filter(filepath => path.extname(filepath) === '.js')
    if (resourcesKeys && resourcesKeys.length) {
      process.UNI_CONFUSION = resourcesKeys.map(filepath =>
        normalizePath(path.resolve(process.env.UNI_INPUT_DIR, filepath))
      )
    }
fxy060608's avatar
fxy060608 已提交
216
  }
fxy060608's avatar
fxy060608 已提交
217 218 219
} else { // 其他平台,待确认配置方案
  if (
    manifestJsonObj['app-plus'] &&
220
    manifestJsonObj['app-plus']['nvueCompiler'] === 'weex'
fxy060608's avatar
fxy060608 已提交
221
  ) {
222
    isNVueCompiler = false
fxy060608's avatar
fxy060608 已提交
223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238
  }
}

if (isNVueCompiler) {
  process.env.UNI_USING_NVUE_COMPILER = true
}

if (platformOptions.usingComponents === true) {
  if (process.env.UNI_PLATFORM !== 'h5') {
    process.env.UNI_USING_COMPONENTS = true
  }
  if (process.env.UNI_PLATFORM === 'app-plus') {
    process.env.UNI_USING_V8 = true
  }
}

fxy060608's avatar
fxy060608 已提交
239
if (
240 241
  process.env.UNI_USING_COMPONENTS ||
  process.env.UNI_PLATFORM === 'h5'
fxy060608's avatar
fxy060608 已提交
242
) { // 自定义组件模式或 h5 平台
243 244 245 246 247
  const uniStatistics = Object.assign(
    manifestJsonObj.uniStatistics || {},
    platformOptions.uniStatistics || {}
  )

248 249 250
  if (uniStatistics.enable !== false) {
    process.env.UNI_USING_STAT = true
    if (!process.UNI_STAT_CONFIG.appid && process.env.NODE_ENV === 'production') {
251 252 253 254 255 256 257
      console.log()
      console.warn(`当前应用未配置Appid,无法使用uni统计,详情参考:https://ask.dcloud.net.cn/article/36303`)
      console.log()
    }
  }
}

fxy060608's avatar
fxy060608 已提交
258 259 260 261 262 263 264 265 266
if (process.env.UNI_USING_COMPONENTS) { // 是否启用分包优化
  if (platformOptions.optimization) {
    if (
      isSupportSubPackages() &&
      platformOptions.optimization.subPackages &&
      Object.keys(process.UNI_SUBPACKAGES).length
    ) {
      process.env.UNI_OPT_SUBPACKAGES = true
    }
fxy060608's avatar
fxy060608 已提交
267 268
  }
}
269

270 271
const warningMsg =
  usingComponentsAbsent
雪洛's avatar
雪洛 已提交
272 273
    ? `该应用之前可能是非自定义组件模式,目前以自定义组件模式运行。非自定义组件已于2019年11月1日起停止支持。详见:https://ask.dcloud.net.cn/article/36385`
    : `uni-app已于2019年11月1日起停止支持非自定义组件模式 [详情](https://ask.dcloud.net.cn/article/36385)`
274 275

const needWarning = !platformOptions.usingComponents || usingComponentsAbsent
fxy060608's avatar
fxy060608 已提交
276
let hasNVue = false
fxy060608's avatar
fxy060608 已提交
277
// 输出编译器版本等信息
fxy060608's avatar
fxy060608 已提交
278
if (process.env.UNI_USING_NATIVE || process.env.UNI_USING_V3_NATIVE) {
fxy060608's avatar
fxy060608 已提交
279 280
  console.log('当前nvue编译模式' + (process.env.UNI_USING_V3_NATIVE ? '(v3)' : '') + '' + (isNVueCompiler ? 'uni-app'
    : 'weex') +
fxy060608's avatar
fxy060608 已提交
281
    ' 。编译模式差异见:https://ask.dcloud.net.cn/article/36074')
fxy060608's avatar
fxy060608 已提交
282
} else if (process.env.UNI_PLATFORM !== 'h5' && process.env.UNI_PLATFORM !== 'quickapp') {
fxy060608's avatar
fxy060608 已提交
283 284 285 286 287
  try {
    let info = ''
    if (process.env.UNI_PLATFORM === 'app-plus') {
      const pagesPkg = require('@dcloudio/webpack-uni-pages-loader/package.json')
      if (pagesPkg) {
fxy060608's avatar
fxy060608 已提交
288 289
        const v3Tips = `(v3)详见:https://ask.dcloud.net.cn/article/36599。`
        info = '编译器版本:' + pagesPkg['uni-app']['compilerVersion'] + (process.env.UNI_USING_V3 ? v3Tips : '')
fxy060608's avatar
fxy060608 已提交
290
      }
fxy060608's avatar
fxy060608 已提交
291 292 293
      if (process.env.UNI_USING_V3) {
        console.log(info)
      } else {
fxy060608's avatar
fxy060608 已提交
294 295 296 297 298 299 300 301 302 303 304 305
        const glob = require('glob')
        hasNVue = !!glob.sync('pages/**/*.nvue', {
          cwd: process.env.UNI_INPUT_DIR
        }).length
        if (hasNVue) {
          console.log(info)
          if (needWarning) {
            console.log(warningMsg)
          }
          console.log('当前nvue编译模式:' + (isNVueCompiler ? 'uni-app' : 'weex') +
            ' 。编译模式差异见:https://ask.dcloud.net.cn/article/36074')
        } else {
306
          console.log(info)
fxy060608's avatar
fxy060608 已提交
307 308 309
          if (needWarning) {
            console.log(warningMsg)
          }
310
        }
fxy060608's avatar
fxy060608 已提交
311 312
      }
    } else {
313
      if (needWarning) {
314
        console.log(warningMsg)
315
      }
fxy060608's avatar
fxy060608 已提交
316 317 318
    }
  } catch (e) {}
}
fxy060608's avatar
fxy060608 已提交
319
if (process.env.NODE_ENV !== 'production') { // 运行模式性能提示
fxy060608's avatar
fxy060608 已提交
320
  let perfMsg = `请注意运行模式下,因日志输出、sourcemap以及未压缩源码等原因,性能和包体积,均不及发行模式。`
fxy060608's avatar
fxy060608 已提交
321 322 323
  if (hasNVue) { // app-nvue
    perfMsg = perfMsg + `尤其是app-nvue的sourcemap影响较大`
  } else if (process.env.UNI_PLATFORM.indexOf('mp-') === 0) { // 小程序
fxy060608's avatar
fxy060608 已提交
324
    perfMsg = perfMsg + `若要正式发布,请点击发行菜单或使用cli发布命令进行发布`
fxy060608's avatar
fxy060608 已提交
325 326 327
  }
  console.log(perfMsg)
}
fxy060608's avatar
fxy060608 已提交
328 329 330

const moduleAlias = require('module-alias')

331
// 将 template-compiler 指向修订后的版本
fxy060608's avatar
fxy060608 已提交
332
moduleAlias.addAlias('vue-template-compiler', '@dcloudio/vue-cli-plugin-uni/packages/vue-template-compiler')
fxy060608's avatar
fxy060608 已提交
333
moduleAlias.addAlias('@megalo/template-compiler', '@dcloudio/vue-cli-plugin-uni/packages/@megalo/template-compiler')
334
moduleAlias.addAlias('mpvue-template-compiler', '@dcloudio/vue-cli-plugin-uni/packages/mpvue-template-compiler')
335 336
// vue-loader
moduleAlias.addAlias('vue-loader', '@dcloudio/vue-cli-plugin-uni/packages/vue-loader')
fxy060608's avatar
fxy060608 已提交
337

fxy060608's avatar
fxy060608 已提交
338 339
if (process.env.UNI_USING_V3 && process.env.UNI_PLATFORM === 'app-plus') {
  moduleAlias.addAlias('vue-style-loader', '@dcloudio/vue-cli-plugin-uni/packages/app-vue-style-loader')
340
}
fxy060608's avatar
fxy060608 已提交
341

Q
qiang 已提交
342 343 344
if (process.env.UNI_PLATFORM === 'h5') {
  moduleAlias.addAlias('vue-style-loader', '@dcloudio/vue-cli-plugin-uni/packages/h5-vue-style-loader')
}
fxy060608's avatar
fxy060608 已提交
345

fxy060608's avatar
fxy060608 已提交
346
if (process.env.UNI_PLATFORM === 'mp-toutiao') {
347 348 349 350 351 352 353
  // !important 始终带有一个空格
  moduleAlias.addAlias(
    'postcss-normalize-whitespace',
    '@dcloudio/vue-cli-plugin-uni/packages/postcss-normalize-whitespace'
  )
}

fxy060608's avatar
fxy060608 已提交
354 355 356 357 358 359 360 361 362 363 364 365 366 367 368
if (runByHBuilderX) {
  const oldError = console.error
  console.error = function (msg) {
    if (typeof msg === 'string' && msg.includes(
      '[BABEL] Note: The code generator has deoptimised the styling of')) {
      const filePath = msg.replace('[BABEL] Note: The code generator has deoptimised the styling of ', '').split(
        ' as ')[0]
      console.log('[警告] `' + path.relative(process.env.UNI_INPUT_DIR, filePath) +
        '` 文件体积超过 500KB,已跳过压缩以及 ES6 转 ES5 的处理,手机端使用过大的js库影响性能。')
    } else {
      oldError.apply(console, arguments)
      // TODO 如果是首次运行遇到错误直接退出
    }
  }
}
369

fxy060608's avatar
fxy060608 已提交
370 371
if (
  process.env.UNI_USING_CACHE &&
fxy060608's avatar
fxy060608 已提交
372
  process.env.UNI_PLATFORM !== 'h5' &&
fxy060608's avatar
fxy060608 已提交
373
  !process.env.UNI_USING_V3 &&
fxy060608's avatar
fxy060608 已提交
374 375
  !process.env.UNI_USING_NATIVE &&
  !process.env.UNI_USING_V3_NATIVE
fxy060608's avatar
fxy060608 已提交
376 377
) { // 使用 cache, 拷贝 cache 的 json
  const cacheJsonDir = path.resolve(
fxy060608's avatar
fxy060608 已提交
378
    process.env.UNI_CLI_CONTEXT,
fxy060608's avatar
fxy060608 已提交
379
    'node_modules/.cache/uni-pages-loader/' + process.env.UNI_PLATFORM
fxy060608's avatar
fxy060608 已提交
380 381 382 383
  )
  if (!fs.existsSync(cacheJsonDir)) { //  创建 cache 目录
    mkdirp(cacheJsonDir)
  } else {
fxy060608's avatar
fxy060608 已提交
384
    require('@dcloudio/uni-cli-shared/lib/cache').restore()
fxy060608's avatar
fxy060608 已提交
385 386 387
  }
}

388
const {
389
  initAutoImportComponents,
fxy060608's avatar
fxy060608 已提交
390
  initAutoImportScanComponents
391 392 393 394 395 396 397
} = require('@dcloudio/uni-cli-shared/lib/pages')

process.UNI_AUTO_SCAN_COMPONENTS = !(pagesJsonObj.easycom && pagesJsonObj.easycom.autoscan === false)
initAutoImportComponents(pagesJsonObj.easycom)
if (process.UNI_AUTO_SCAN_COMPONENTS) {
  initAutoImportScanComponents()
}
398

fxy060608's avatar
fxy060608 已提交
399
runByHBuilderX && console.log(`正在编译中...`)
fxy060608's avatar
fxy060608 已提交
400 401 402

module.exports = {
  manifestPlatformOptions: platformOptions
403
}