index.js 11.1 KB
Newer Older
fxy060608's avatar
fxy060608 已提交
1 2 3 4 5 6
const path = require('path')
const webpack = require('webpack')

const {
  parseEntry,
  getMainEntry,
7
  normalizePath,
fxy060608's avatar
fxy060608 已提交
8
  getPlatformExts,
fxy060608's avatar
fxy060608 已提交
9 10
  getPlatformCssnano,
  getPlatformStat,
雪洛's avatar
雪洛 已提交
11 12
  getPlatformPush,
  getPlatformUniCloud
fxy060608's avatar
fxy060608 已提交
13 14
} = require('@dcloudio/uni-cli-shared')

fxy060608's avatar
fxy060608 已提交
15
const WebpackUniAppPlugin = require('../../packages/webpack-uni-app-loader/plugin/index')
fxy060608's avatar
fxy060608 已提交
16

fxy060608's avatar
fxy060608 已提交
17
const modifyVueLoader = require('../vue-loader')
fxy060608's avatar
fxy060608 已提交
18

fxy060608's avatar
fxy060608 已提交
19
const {
fxy060608's avatar
fxy060608 已提交
20
  createTemplateCacheLoader
fxy060608's avatar
fxy060608 已提交
21
} = require('../cache-loader')
fxy060608's avatar
fxy060608 已提交
22

fxy060608's avatar
fxy060608 已提交
23
function createUniMPPlugin () {
24
  const WebpackUniMPPlugin = require('@dcloudio/webpack-uni-mp-loader/lib/plugin/index-new')
fxy060608's avatar
fxy060608 已提交
25 26 27
  return new WebpackUniMPPlugin()
}

S
songyu 已提交
28
const createWxMpIndependentPlugins = require('@dcloudio/uni-mp-weixin/lib/createIndependentPlugin')
29

fxy060608's avatar
fxy060608 已提交
30
function getProvides () {
fxy060608's avatar
fxy060608 已提交
31
  const uniPath = require('@dcloudio/uni-cli-shared/lib/platform').getMPRuntimePath()
fxy060608's avatar
fxy060608 已提交
32
  const uniCloudPath = path.resolve(__dirname, '../../packages/uni-cloud/dist/index.js')
fxy060608's avatar
fxy060608 已提交
33
  const provides = {
fxy060608's avatar
fxy060608 已提交
34 35
    uni: [uniPath, 'default'],
    uniCloud: [uniCloudPath, 'default']
fxy060608's avatar
fxy060608 已提交
36 37
  }

fxy060608's avatar
fxy060608 已提交
38 39 40 41 42
  if (process.env.UNI_USING_VUE3) {
    provides.uni = ['@dcloudio/uni-' + process.env.UNI_PLATFORM + '/dist/uni.api.esm.js', 'default']
    provides.createMiniProgramApp = [uniPath, 'createApp']
  }

fxy060608's avatar
fxy060608 已提交
43
  if (process.env.UNI_USING_COMPONENTS) {
fxy060608's avatar
fxy060608 已提交
44 45
    if (process.env.UNI_SUBPACKGE) {
      provides.createApp = [uniPath, 'createSubpackageApp']
46 47
    } else if (process.env.UNI_MP_PLUGIN) {
      provides.createApp = [uniPath, 'createPlugin']
fxy060608's avatar
fxy060608 已提交
48 49 50
    } else {
      provides.createApp = [uniPath, 'createApp']
    }
fxy060608's avatar
fxy060608 已提交
51 52
    provides.createPage = [uniPath, 'createPage']
    provides.createComponent = [uniPath, 'createComponent']
fxy060608's avatar
fxy060608 已提交
53 54 55 56 57 58
  }

  if (
    process.env.UNI_PLATFORM === 'app-plus' &&
    process.env.UNI_USING_V8
  ) {
fxy060608's avatar
fxy060608 已提交
59
    provides.__f__ = [path.resolve(__dirname, '../format-log.js'), 'default']
60

fxy060608's avatar
fxy060608 已提交
61
    const cryptoProvide = [path.resolve(__dirname, '../crypto.js'), 'default']
fxy060608's avatar
fxy060608 已提交
62
    provides.crypto = cryptoProvide
63 64
    provides['window.crypto'] = cryptoProvide
    provides['global.crypto'] = cryptoProvide
fxy060608's avatar
fxy060608 已提交
65 66 67 68 69 70 71 72
  }

  // TODO 目前依赖库 megalo 通过判断 wx 对象是否存在来识别平台做不同处理
  if (
    process.env.UNI_PLATFORM !== 'mp-qq' &&
    process.env.UNI_PLATFORM !== 'mp-weixin' &&
    process.env.UNI_PLATFORM !== 'app-plus'
  ) { // 非微信小程序,自动注入 wx 对象
fxy060608's avatar
fxy060608 已提交
73
    provides.wx = provides.uni
fxy060608's avatar
fxy060608 已提交
74 75 76 77
  }
  return provides
}

fxy060608's avatar
fxy060608 已提交
78 79
function processWxss (name, assets) {
  const dirname = path.dirname(name)
80
  const mainWxssCode = `@import "${normalizePath(path.relative(dirname, 'common/main.wxss'))}";`
fxy060608's avatar
fxy060608 已提交
81 82 83 84 85 86 87 88 89 90 91
  const code = `${mainWxssCode}` + assets[name].source().toString()
  assets[name] = {
    size () {
      return Buffer.byteLength(code, 'utf8')
    },
    source () {
      return code
    }
  }
}

92 93
const parseRequirePath = path => path.startsWith('common') ? `./${path}` : path

fxy060608's avatar
fxy060608 已提交
94 95
function procssJs (name, assets, hasVendor) {
  const dirname = path.dirname(name)
96
  const runtimeJsCode = `require('${normalizePath(parseRequirePath(path.relative(dirname, 'common/runtime.js')))}');`
fxy060608's avatar
fxy060608 已提交
97 98
  const vendorJsCode = hasVendor
    ? `require('${normalizePath(parseRequirePath(path.relative(dirname, 'common/vendor.js')))}');` : ''
99
  const mainJsCode = `require('${normalizePath(parseRequirePath(path.relative(dirname, 'common/main.js')))}');`
fxy060608's avatar
fxy060608 已提交
100 101 102 103 104 105 106 107 108 109 110
  const code = `${runtimeJsCode}${vendorJsCode}${mainJsCode}` + assets[name].source().toString()
  assets[name] = {
    size () {
      return Buffer.byteLength(code, 'utf8')
    },
    source () {
      return code
    }
  }
}

fxy060608's avatar
fxy060608 已提交
111 112 113 114
class PreprocessAssetsPlugin {
  apply (compiler) {
    compiler.hooks.emit.tap('PreprocessAssetsPlugin', compilation => {
      const assets = compilation.assets
fxy060608's avatar
fxy060608 已提交
115
      const hasMainWxss = assets['common/main.wxss']
fxy060608's avatar
fxy060608 已提交
116 117 118 119 120
      const hasVendor = assets['common/vendor.js']
      Object.keys(assets).forEach(name => {
        if (name.startsWith('common')) {
          return
        }
fxy060608's avatar
fxy060608 已提交
121 122 123 124 125
        const extname = path.extname(name)
        if (extname === '.wxss' && hasMainWxss && process.UNI_ENTRY[name.replace(extname, '')]) {
          processWxss(name, assets)
        } else if (extname === '.js') {
          procssJs(name, assets, hasVendor)
fxy060608's avatar
fxy060608 已提交
126 127
        }
      })
fxy060608's avatar
fxy060608 已提交
128
      // delete assets['common/main.js']
fxy060608's avatar
fxy060608 已提交
129 130 131 132 133 134 135 136 137
      delete assets['app.js']
      delete assets['app.json']
      delete assets['app.wxss']
      delete assets['project.config.json']
    })
  }
}

function initSubpackageConfig (webpackConfig, vueOptions) {
138
  if (process.env.UNI_OUTPUT_DEFAULT_DIR === process.env.UNI_OUTPUT_DIR) { // 未自定义output
fxy060608's avatar
fxy060608 已提交
139 140
    process.env.UNI_OUTPUT_DIR = path.resolve(process.env.UNI_OUTPUT_DIR, (process.env.UNI_SUBPACKGE || process.env
      .UNI_MP_PLUGIN))
141
  }
fxy060608's avatar
fxy060608 已提交
142 143
  vueOptions.outputDir = process.env.UNI_OUTPUT_DIR
  webpackConfig.output.path(process.env.UNI_OUTPUT_DIR)
144
  webpackConfig.output.jsonpFunction('webpackJsonp_' + (process.env.UNI_SUBPACKGE || process.env.UNI_MP_PLUGIN))
fxy060608's avatar
fxy060608 已提交
145 146
}

147 148 149 150
function addToUniEntry (fileName) {
  fileName && (process.UNI_ENTRY[fileName.split('.')[0]] = path.resolve(process.env.UNI_INPUT_DIR, fileName))
}

fxy060608's avatar
fxy060608 已提交
151 152 153 154
module.exports = {
  vueConfig: {
    parallel: false
  },
fxy060608's avatar
fxy060608 已提交
155
  webpackConfig (webpackConfig, vueOptions, api) {
fxy060608's avatar
fxy060608 已提交
156 157 158 159 160 161 162 163 164 165
    if (!webpackConfig.optimization) {
      webpackConfig.optimization = {}
    }
    // disable noEmitOnErrors
    webpackConfig.optimization.noEmitOnErrors = false

    webpackConfig.optimization.runtimeChunk = {
      name: 'common/runtime'
    }

fxy060608's avatar
fxy060608 已提交
166
    webpackConfig.optimization.splitChunks = require('../split-chunks')()
fxy060608's avatar
fxy060608 已提交
167 168 169

    parseEntry()

fxy060608's avatar
fxy060608 已提交
170
    const statCode = getPlatformStat()
fxy060608's avatar
fxy060608 已提交
171
    const pushCode = getPlatformPush()
雪洛's avatar
雪洛 已提交
172
    const uniCloudCode = getPlatformUniCloud()
fxy060608's avatar
fxy060608 已提交
173

174
    let beforeCode = 'import \'uni-pages\';'
fxy060608's avatar
fxy060608 已提交
175 176 177 178

    const plugins = [
      new WebpackUniAppPlugin(),
      createUniMPPlugin(),
179 180
      new webpack.ProvidePlugin(getProvides()),
      ...createWxMpIndependentPlugins()
fxy060608's avatar
fxy060608 已提交
181 182
    ]

183
    if ((process.env.UNI_SUBPACKGE || process.env.UNI_MP_PLUGIN) && process.env.UNI_SUBPACKGE !== 'main') {
fxy060608's avatar
fxy060608 已提交
184 185
      plugins.push(new PreprocessAssetsPlugin())
    }
fxy060608's avatar
fxy060608 已提交
186

187
    {
fxy060608's avatar
fxy060608 已提交
188
      const globalEnv = process.env.UNI_PLATFORM === 'mp-alipay' ? 'my' : 'wx';
189 190 191 192 193
      [].concat(
        process.env.UNI_MP_PLUGIN
          ? process.env.UNI_MP_PLUGIN_MAIN
          : JSON.parse(process.env.UNI_MP_PLUGIN_EXPORT)
      ).forEach(fileName => addToUniEntry(fileName))
雪洛's avatar
雪洛 已提交
194 195
      beforeCode += `
// @ts-ignore
fxy060608's avatar
fxy060608 已提交
196
${globalEnv}.__webpack_require_UNI_MP_PLUGIN__ = __webpack_require__;`
197 198
    }

fxy060608's avatar
fxy060608 已提交
199 200 201 202 203 204 205 206
    const alias = { // 仅 mp-weixin
      'mpvue-page-factory': require.resolve(
        '@dcloudio/vue-cli-plugin-uni/packages/mpvue-page-factory')
    }

    if (process.env.UNI_USING_VUE3) {
      alias.vuex = require.resolve('@dcloudio/vue-cli-plugin-uni/packages/vuex')
      alias['@vue/devtools-api'] = require.resolve('@dcloudio/vue-cli-plugin-uni/packages/@vue/devtools-api')
207 208 209

      alias['vue-i18n'] = require.resolve('@dcloudio/vue-cli-plugin-uni/packages/vue3/node_modules/vue-i18n')
      alias['@dcloudio/uni-app'] = require.resolve('@dcloudio/vue-cli-plugin-uni/packages/uni-app')
fxy060608's avatar
fxy060608 已提交
210 211
    }

Q
qiang 已提交
212 213
    // 使用外层依赖的版本
    alias['regenerator-runtime'] = require.resolve('regenerator-runtime')
fxy060608's avatar
fxy060608 已提交
214
    const output = {
fxy060608's avatar
fxy060608 已提交
215
      pathinfo: true,
fxy060608's avatar
fxy060608 已提交
216 217 218 219 220
      filename: '[name].js',
      chunkFilename: '[id].js',
      globalObject: process.env.UNI_PLATFORM === 'mp-alipay' ? 'my' : 'global'
      // sourceMapFilename: '../.sourcemap/' + process.env.UNI_PLATFORM + '/[name].js.map'
    }
fxy060608's avatar
fxy060608 已提交
221
    if (process.env.NODE_ENV === 'production' || process.env.UNI_MINIMIZE === 'true') {
fxy060608's avatar
fxy060608 已提交
222
      output.pathinfo = false
fxy060608's avatar
fxy060608 已提交
223
    }
fxy060608's avatar
fxy060608 已提交
224
    return {
fxy060608's avatar
fxy060608 已提交
225
      mode: process.env.NODE_ENV === 'production' ? 'production' : 'development',
fxy060608's avatar
fxy060608 已提交
226 227 228
      entry () {
        return process.UNI_ENTRY
      },
fxy060608's avatar
fxy060608 已提交
229
      output,
fxy060608's avatar
fxy060608 已提交
230 231
      performance: {
        hints: false
fxy060608's avatar
fxy060608 已提交
232 233 234
      },
      resolve: {
        extensions: ['.nvue'],
fxy060608's avatar
fxy060608 已提交
235
        alias
fxy060608's avatar
fxy060608 已提交
236 237 238 239 240
      },
      module: {
        rules: [{
          test: path.resolve(process.env.UNI_INPUT_DIR, getMainEntry()),
          use: [{
241
            loader: path.resolve(__dirname, '../../packages/wrap-loader'),
fxy060608's avatar
fxy060608 已提交
242 243
            options: {
              before: [
雪洛's avatar
雪洛 已提交
244
                beforeCode + require('../util').getAutomatorCode() + statCode + pushCode + uniCloudCode
fxy060608's avatar
fxy060608 已提交
245 246 247
              ]
            }
          }, {
fxy060608's avatar
fxy060608 已提交
248 249 250 251 252 253 254 255 256 257 258
            loader: '@dcloudio/webpack-uni-mp-loader/lib/main'
          }]
        }, {
          resourceQuery: /vue&type=script/,
          use: [{
            loader: '@dcloudio/webpack-uni-mp-loader/lib/script'
          }]
        }, {
          resourceQuery: /vue&type=template/,
          use: [{
            loader: '@dcloudio/webpack-uni-mp-loader/lib/template'
259 260
          }, {
            loader: '@dcloudio/vue-cli-plugin-uni/packages/webpack-uni-app-loader/page-meta'
fxy060608's avatar
fxy060608 已提交
261
          }]
fxy060608's avatar
fxy060608 已提交
262
        }, createTemplateCacheLoader(api), {
fxy060608's avatar
fxy060608 已提交
263 264 265
          resourceQuery: [
            /lang=wxs/,
            /lang=filter/,
fxy060608's avatar
fxy060608 已提交
266
            /lang=sjs/,
fxy060608's avatar
fxy060608 已提交
267 268
            /blockType=wxs/,
            /blockType=filter/,
fxy060608's avatar
fxy060608 已提交
269
            /blockType=sjs/
fxy060608's avatar
fxy060608 已提交
270
          ],
fxy060608's avatar
fxy060608 已提交
271 272 273 274
          use: [{
            loader: require.resolve(
              '@dcloudio/vue-cli-plugin-uni/packages/webpack-uni-filter-loader')
          }]
fxy060608's avatar
fxy060608 已提交
275 276
        }]
      },
fxy060608's avatar
fxy060608 已提交
277
      plugins
fxy060608's avatar
fxy060608 已提交
278 279
    }
  },
fxy060608's avatar
fxy060608 已提交
280
  chainWebpack (webpackConfig, vueOptions, api) {
fxy060608's avatar
fxy060608 已提交
281 282 283 284 285 286 287
    if (process.env.UNI_PLATFORM === 'mp-baidu') {
      webpackConfig.module
        .rule('js')
        .exclude
        .add(/\.filter\.js$/)
    }

fxy060608's avatar
fxy060608 已提交
288
    const compilerOptions = process.env.UNI_USING_COMPONENTS ? {} : require('../mp-compiler-options')
fxy060608's avatar
fxy060608 已提交
289

290
    modifyVueLoader(webpackConfig, {}, compilerOptions, api)
fxy060608's avatar
fxy060608 已提交
291

fxy060608's avatar
fxy060608 已提交
292 293
    const styleExt = getPlatformExts().style

fxy060608's avatar
fxy060608 已提交
294 295
    webpackConfig.plugin('extract-css')
      .init((Plugin, args) => new Plugin({
fxy060608's avatar
fxy060608 已提交
296
        filename: '[name]' + styleExt
fxy060608's avatar
fxy060608 已提交
297 298
      }))

fxy060608's avatar
fxy060608 已提交
299 300 301 302
    if (
      process.env.NODE_ENV === 'production' &&
      process.env.UNI_PLATFORM !== 'app-plus'
    ) {
Q
qiang 已提交
303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326
      // webpack5 不再使用 OptimizeCssnanoPlugin,改用 CssMinimizerPlugin
      if (webpack.version[0] > 4) {
        webpackConfig.optimization.minimizer('css').tap(args => {
          args[0].test = new RegExp(`\\${styleExt}$`)
          return args
        })
      } else {
        const OptimizeCssnanoPlugin = require('../../packages/@intervolga/optimize-cssnano-plugin/index.js')
        webpackConfig.plugin('optimize-css')
          .init((Plugin, args) => new OptimizeCssnanoPlugin({
            sourceMap: false,
            filter (assetName) {
              return path.extname(assetName) === styleExt
            },
            cssnanoOptions: {
              preset: [
                'default',
                Object.assign({}, getPlatformCssnano(), {
                  discardComments: true
                })
              ]
            }
          }))
      }
fxy060608's avatar
fxy060608 已提交
327 328
    }

329
    if (process.env.UNI_SUBPACKGE || process.env.UNI_MP_PLUGIN) {
fxy060608's avatar
fxy060608 已提交
330 331 332
      initSubpackageConfig(webpackConfig, vueOptions)
    }

fxy060608's avatar
fxy060608 已提交
333 334 335 336 337 338
    webpackConfig.plugins.delete('hmr')
    webpackConfig.plugins.delete('html')
    webpackConfig.plugins.delete('copy')
    webpackConfig.plugins.delete('preload')
    webpackConfig.plugins.delete('prefetch')
  }
雪洛's avatar
雪洛 已提交
339
}