configure-webpack.js 10.9 KB
Newer Older
fxy060608's avatar
fxy060608 已提交
1 2 3 4 5 6 7 8
const fs = require('fs')
const path = require('path')
const webpack = require('webpack')
const RuleSet = require('webpack/lib/RuleSet')
const CopyWebpackPlugin = require('copy-webpack-plugin')

const merge = require('webpack-merge')

fxy060608's avatar
fxy060608 已提交
9 10 11 12
const {
  getPartialIdentifier
} = require('./util')

fxy060608's avatar
fxy060608 已提交
13 14 15 16 17 18 19 20
function resolve (dir) {
  return path.resolve(__dirname, '..', dir)
}

function resolveModule (dir) {
  return path.resolve(__dirname, '../../..', dir)
}

fxy060608's avatar
fxy060608 已提交
21
module.exports = function configureWebpack (platformOptions, manifestPlatformOptions, vueOptions, api) {
fxy060608's avatar
fxy060608 已提交
22 23 24 25 26 27 28 29
  const {
    runByHBuilderX, // 使用 HBuilderX 运行
    isInHBuilderX, // 在 HBuilderX 的插件中
    hasModule,
    jsPreprocessOptions,
    htmlPreprocessOptions
  } = require('@dcloudio/uni-cli-shared')

fxy060608's avatar
fxy060608 已提交
30 31 32 33
  const {
    getPlatformVue
  } = require('@dcloudio/uni-cli-shared/lib/platform')

fxy060608's avatar
fxy060608 已提交
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
  const {
    getCopyWebpackPluginOptions
  } = require('./copy-webpack-options')

  function createMatcher (fakeFile) {
    return (rule, i) => {
      const clone = Object.assign({}, rule)
      delete clone.include
      const normalized = RuleSet.normalizeRule(clone, {}, '')
      return (
        !rule.enforce &&
        normalized.resource &&
        normalized.resource(fakeFile)
      )
    }
  }

  function updateJsLoader (rawRules, fakeFile, checkLoaderRegex, loader) {
    const matchRule = rawRules.find(createMatcher(fakeFile))

    const matchUse = matchRule.use

    const matchLoaderUseIndex = matchUse.findIndex(u => {
      return checkLoaderRegex.test(u.loader)
    })

    if (matchLoaderUseIndex < 0) {
      throw new Error(`No matching use for ${fakeFile}`)
    }

    matchUse.push(loader)
  }

  const userTsConfigJson = path.resolve(process.env.UNI_INPUT_DIR, 'tsconfig.json')
  const defaultTsConfigJson = path.resolve(process.env.UNI_CLI_CONTEXT, 'tsconfig.json')

  const tsConfigJsonFile = fs.existsSync(userTsConfigJson) ? userTsConfigJson : defaultTsConfigJson

  const tsLoaderOptions = {
    context: process.env.UNI_INPUT_DIR,
    configFile: tsConfigJsonFile,
    transpileOnly: false,
    compilerOptions: {
      baseUrl: process.env.UNI_INPUT_DIR,
      typeRoots: [resolveModule('@dcloudio/types'), resolveModule('@types')],
      types: [
        'uni-app',
        'webpack-env'
      ],
      paths: {
        '@/*': [
          path.join(process.env.UNI_INPUT_DIR, '*')
        ],
fxy060608's avatar
fxy060608 已提交
87
        vue: [
fxy060608's avatar
fxy060608 已提交
88 89
          resolveModule('vue')
        ],
fxy060608's avatar
fxy060608 已提交
90
        vuex: [
fxy060608's avatar
fxy060608 已提交
91 92 93 94 95 96 97 98
          resolveModule('vuex')
        ],
        'vue-class-component': [
          resolveModule('vue-class-component')
        ],
        'vue-property-decorator': [
          resolveModule('vue-property-decorator')
        ],
fxy060608's avatar
fxy060608 已提交
99
        tslib: [
fxy060608's avatar
fxy060608 已提交
100 101 102 103 104 105 106 107 108 109 110 111
          resolveModule('tslib')
        ],
        'mpvue-page-factory': [
          resolveModule('@dcloudio/vue-cli-plugin-uni/packages/mpvue-page-factory')
        ]
      }
    },
    errorFormatter (error, colors) {
      const messageColor = error.severity === 'warning' ? colors.bold.yellow : colors.bold.red
      const filePath = path.relative(process.env.UNI_INPUT_DIR, error.file).replace('.vue.ts', '.vue')
      if (error.code === 2307 && error.content.includes('.vue')) {
        error.content = error.content.replace('Cannot find module ', '') +
fxy060608's avatar
fxy060608 已提交
112
          ' script 节点必须使用 lang="ts",文档参考地址:https://uniapp.dcloud.io/frame?id=vue-ts'
fxy060608's avatar
fxy060608 已提交
113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142
      }
      return messageColor(
        `[tsl] ERROR at ${filePath}:${error.line}
  TS${error.code}:${error.content}`
      )
    }
  }

  function updateTsLoader (rawRules, fakeFile, loader) {
    const matchRule = rawRules.find(createMatcher(fakeFile))
    if (matchRule && matchRule.use) {
      if (runByHBuilderX) {
        matchRule.use.forEach(matchUse => {
          if (matchUse.loader === 'ts-loader') {
            Object.assign(matchUse.options, tsLoaderOptions)
          }
        })
      }
      matchRule.use.push(loader)
    }
  }

  function removeForkTsCheckerWebpackPlugin (rawPlugins) {
    if (isInHBuilderX && hasModule('fork-ts-checker-webpack-plugin')) {
      const pluginIndex = rawPlugins.findIndex(rawPlugin => rawPlugin.vue && rawPlugin.typescriptVersion)
      if (pluginIndex !== -1) { // 移除fork-ts-checker-webpack-plugin
        rawPlugins.splice(pluginIndex, 1)
      }
    }
  }
143 144
  const babelLoaderRe = /^babel-loader|(\/|\\|@)babel-loader/
  const cacheLoaderRe = /^cache-loader|(\/|\\|@)cache-loader/
fxy060608's avatar
fxy060608 已提交
145 146 147 148 149 150
  return function (webpackConfig) {
    // disable js cache-loader
    const rawRules = webpackConfig.module.rules
    for (let i = rawRules.length - 1; i >= 0; i--) {
      const uses = rawRules[i].use
      if (Array.isArray(uses)) {
151 152
        if (uses.find(use => babelLoaderRe.test(use.loader))) {
          const index = uses.findIndex(use => cacheLoaderRe.test(use.loader))
fxy060608's avatar
fxy060608 已提交
153 154 155 156 157 158 159 160
          if (process.env.UNI_USING_CACHE) {
            Object.assign(uses[index].options, api.genCacheConfig(
              'babel-loader/' + process.env.UNI_PLATFORM,
              getPartialIdentifier()
            ))
          } else {
            uses.splice(index, 1)
          }
fxy060608's avatar
fxy060608 已提交
161 162 163 164 165
        }
      }
    }

    // js preprocess
166
    updateJsLoader(rawRules, 'foo.js', babelLoaderRe, {
fxy060608's avatar
fxy060608 已提交
167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183
      loader: resolve('packages/webpack-preprocess-loader'),
      options: jsPreprocessOptions
    })
    // ts options and preprocess
    updateTsLoader(rawRules, 'foo.ts', {
      loader: resolve('packages/webpack-preprocess-loader'),
      options: jsPreprocessOptions
    })
    updateTsLoader(rawRules, 'foo.tsx', {
      loader: resolve('packages/webpack-preprocess-loader'),
      options: jsPreprocessOptions
    })
    // 如果在 HBuilderX 中
    removeForkTsCheckerWebpackPlugin(webpackConfig.plugins)

    let platformWebpackConfig = platformOptions.webpackConfig
    if (typeof platformWebpackConfig === 'function') {
fxy060608's avatar
fxy060608 已提交
184
      platformWebpackConfig = platformWebpackConfig(webpackConfig, vueOptions, api)
fxy060608's avatar
fxy060608 已提交
185 186 187 188 189
    }
    // 移除 node_modules 目录,避免受路径上的 node_modules 影响
    webpackConfig.resolve.modules = webpackConfig.resolve.modules.filter(module => module !==
      'node_modules')

fxy060608's avatar
fxy060608 已提交
190 191 192 193 194
    const plugins = []

    const isAppView = process.env.UNI_PLATFORM === 'app-plus' &&
      vueOptions.pluginOptions &&
      vueOptions.pluginOptions['uni-app-plus'] &&
fxy060608's avatar
fxy060608 已提交
195
      vueOptions.pluginOptions['uni-app-plus'].view
fxy060608's avatar
fxy060608 已提交
196 197 198 199

    if (!isAppView) { // app-plus view不需要copy
      plugins.push(new CopyWebpackPlugin(getCopyWebpackPluginOptions(manifestPlatformOptions, vueOptions)))
    }
200 201 202 203 204 205 206 207 208 209 210 211 212 213 214
    if (!process.env.UNI_SUBPACKGE) {
      try {
        const automatorJson = require.resolve('@dcloudio/uni-automator/dist/automator.json')
        plugins.push(new CopyWebpackPlugin([{
          from: automatorJson,
          to: '../.automator/' + (process.env.UNI_SUB_PLATFORM || process.env.UNI_PLATFORM) +
            '/.automator.json',
          transform (content) {
            if (process.env.UNI_AUTOMATOR_WS_ENDPOINT) {
              return JSON.stringify({
                version: require('@dcloudio/uni-automator/package.json').version,
                wsEndpoint: process.env.UNI_AUTOMATOR_WS_ENDPOINT
              })
            }
            return ''
fxy060608's avatar
fxy060608 已提交
215
          }
216 217 218
        }]))
      } catch (e) {}
    }
fxy060608's avatar
fxy060608 已提交
219

fxy060608's avatar
fxy060608 已提交
220 221 222 223 224 225 226 227 228 229 230 231
    if (process.UNI_SCRIPT_ENV && Object.keys(process.UNI_SCRIPT_ENV).length) {
      // custom define
      const envs = Object.create(null)
      Object.keys(process.UNI_SCRIPT_ENV).forEach(name => {
        envs['process.env.' + name] = JSON.stringify(process.UNI_SCRIPT_ENV[name])
      })
      plugins.push(new webpack.DefinePlugin(envs))
    }

    if (runByHBuilderX) { // 使用 HBuilderX 中运行时,调整错误日志输出
      const WebpackErrorsPlugin = require('../packages/webpack-errors-plugin')
      const onErrors = require('../util/on-errors')
232
      const onWarnings = require('../util/on-warnings')
fxy060608's avatar
fxy060608 已提交
233
      plugins.push(new WebpackErrorsPlugin({
fxy060608's avatar
fxy060608 已提交
234
        onErrors,
235
        onWarnings
fxy060608's avatar
fxy060608 已提交
236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266
      }))
    }

    const rules = [{
      test: path.resolve(process.env.UNI_INPUT_DIR, 'pages.json'),
      use: [{
        loader: 'babel-loader'
      }, {
        loader: '@dcloudio/webpack-uni-pages-loader'
      }],
      type: 'javascript/auto'
    },
    {
      resourceQuery: /vue&type=template/,
      use: [{
        loader: resolve('packages/webpack-preprocess-loader'),
        options: htmlPreprocessOptions
      }]
    }
    ]

    if (!process.env.UNI_USING_COMPONENTS) { // 新版本,在 script-loader 中处理(为了避免 babel generator 移除部分条件编译代码)
      rules.push({
        resourceQuery: /vue&type=script/,
        use: [{
          loader: resolve('packages/webpack-preprocess-loader'),
          options: jsPreprocessOptions
        }]
      })
    }

fxy060608's avatar
fxy060608 已提交
267 268 269
    if (process.env.NODE_ENV === 'development') {
      const sourceMap = require('@dcloudio/uni-cli-shared/lib/source-map')
      let isAppService = false
fxy060608's avatar
fxy060608 已提交
270 271 272 273 274
      if (
        process.env.UNI_PLATFORM === 'app-plus' &&
        vueOptions.pluginOptions &&
        vueOptions.pluginOptions['uni-app-plus']
      ) {
fxy060608's avatar
fxy060608 已提交
275 276 277 278 279 280 281 282 283 284 285 286 287 288
        isAppService = !!vueOptions.pluginOptions['uni-app-plus'].service
      }
      if (process.env.UNI_PLATFORM === 'h5' || isAppService) {
        plugins.push(sourceMap.createEvalSourceMapDevToolPlugin())
      } else if (
        process.env.UNI_PLATFORM.indexOf('mp-') === 0 &&
        process.env.UNI_PLATFORM !== 'mp-baidu' &&
        process.env.UNI_PLATFORM !== 'mp-alipay' &&
        process.env.UNI_PLATFORM !== 'quickapp-webview' // 目前 ov 的开发工具支持 eval 模式
      ) {
        plugins.push(sourceMap.createSourceMapDevToolPlugin(process.env.UNI_PLATFORM === 'mp-weixin'))
      }
    }

fxy060608's avatar
fxy060608 已提交
289
    return merge({
fxy060608's avatar
fxy060608 已提交
290
      devtool: false,
fxy060608's avatar
fxy060608 已提交
291 292 293
      resolve: {
        alias: {
          '@': path.resolve(process.env.UNI_INPUT_DIR),
294
          './@': path.resolve(process.env.UNI_INPUT_DIR), // css中的'@/static/logo.png'会被转换成'./@/static/logo.png'加载
fxy060608's avatar
fxy060608 已提交
295
          vue$: getPlatformVue(vueOptions),
fxy060608's avatar
fxy060608 已提交
296
          'uni-pages': path.resolve(process.env.UNI_INPUT_DIR, 'pages.json'),
fxy060608's avatar
fxy060608 已提交
297
          '@dcloudio/uni-stat': require.resolve('@dcloudio/uni-stat'),
fxy060608's avatar
fxy060608 已提交
298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317
          'uni-stat-config': path.resolve(process.env.UNI_INPUT_DIR, 'pages.json') +
            '?' +
            JSON.stringify({
              type: 'stat'
            })
        },
        modules: [
          process.env.UNI_INPUT_DIR,
          path.resolve(process.env.UNI_INPUT_DIR, 'node_modules')
        ]
      },
      module: {
        noParse: /^(vue|vue-router|vuex|vuex-router-sync)$/,
        rules
      },
      plugins,
      performance: {
        assetFilter (assetFilename) {
          return !(/\.map$/.test(assetFilename)) && !(/vendor/.test(assetFilename))
        }
fxy060608's avatar
fxy060608 已提交
318 319
      },
      watchOptions: require('./util').getWatchOptions()
fxy060608's avatar
fxy060608 已提交
320 321
    }, platformWebpackConfig)
  }
322
}