rollup.config.js 5.5 KB
Newer Older
fxy060608's avatar
fxy060608 已提交
1
import fs from 'fs'
fxy060608's avatar
fxy060608 已提交
2 3 4 5
import path from 'path'
import ts from 'rollup-plugin-typescript2'
import replace from '@rollup/plugin-replace'
import json from '@rollup/plugin-json'
fxy060608's avatar
fxy060608 已提交
6 7 8
import alias from '@rollup/plugin-alias'
import nodeResolve from '@rollup/plugin-node-resolve'
import commonjs from '@rollup/plugin-commonjs'
fxy060608's avatar
fxy060608 已提交
9
import { getBabelOutputPlugin } from '@rollup/plugin-babel'
fxy060608's avatar
fxy060608 已提交
10 11 12 13 14 15 16

if (!process.env.TARGET) {
  throw new Error('TARGET package must be specified via --environment flag.')
}

const packagesDir = path.resolve(__dirname, 'packages')
const packageDir = path.resolve(packagesDir, process.env.TARGET)
fxy060608's avatar
fxy060608 已提交
17
const resolve = (p) => path.resolve(packageDir, p)
fxy060608's avatar
fxy060608 已提交
18 19
const pkg = require(resolve(`package.json`))

fxy060608's avatar
fxy060608 已提交
20 21 22
// ensure TS checks only once for each build
let hasTSChecked = false

fxy060608's avatar
fxy060608 已提交
23
const configs = []
fxy060608's avatar
fxy060608 已提交
24 25

let buildOptions = require(resolve(`build.json`))
fxy060608's avatar
fxy060608 已提交
26 27 28 29 30 31 32 33 34 35 36 37

function normalizeOutput(file, output = {}) {
  return Object.assign(
    {
      file,
      format: file.includes('.cjs.') ? 'cjs' : 'es',
      exports: 'auto',
    },
    output
  )
}

fxy060608's avatar
fxy060608 已提交
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
if (!Array.isArray(buildOptions)) {
  buildOptions = [buildOptions]
}
buildOptions.forEach((buildOption) => {
  Object.keys(buildOption.input).forEach((name) => {
    const files = buildOption.input[name]
    if (Array.isArray(files)) {
      files.forEach((file) => {
        configs.push(
          createConfig(
            name,
            normalizeOutput(resolve(file), buildOption.output),
            buildOption
          )
        )
      })
    } else {
fxy060608's avatar
fxy060608 已提交
55
      configs.push(
fxy060608's avatar
fxy060608 已提交
56 57 58 59 60
        createConfig(
          name,
          normalizeOutput(resolve(buildOption.input[name]), buildOption.output),
          buildOption
        )
fxy060608's avatar
fxy060608 已提交
61
      )
fxy060608's avatar
fxy060608 已提交
62 63
    }
  })
fxy060608's avatar
fxy060608 已提交
64
})
fxy060608's avatar
fxy060608 已提交
65

fxy060608's avatar
fxy060608 已提交
66 67
export default configs

fxy060608's avatar
fxy060608 已提交
68 69 70 71 72 73 74 75 76 77 78 79 80
function resolveTsconfigJson() {
  const tsconfigJsonPath = resolve('tsconfig.json')
  if (
    fs.existsSync(tsconfigJsonPath)
    //  &&
    // require(tsconfigJsonPath).extends === '../../tsconfig.json'
  ) {
    return tsconfigJsonPath
  }
  return path.resolve(__dirname, 'tsconfig.json')
}

function createConfig(entryFile, output, buildOption) {
fxy060608's avatar
fxy060608 已提交
81
  const shouldEmitDeclarations = process.env.TYPES != null && !hasTSChecked
fxy060608's avatar
fxy060608 已提交
82
  const tsPlugin = ts({
fxy060608's avatar
fxy060608 已提交
83 84
    check:
      !process.env.CI && process.env.NODE_ENV === 'production' && !hasTSChecked,
fxy060608's avatar
fxy060608 已提交
85
    tsconfig: resolveTsconfigJson(),
fxy060608's avatar
fxy060608 已提交
86 87 88 89 90
    cacheRoot: path.resolve(__dirname, 'node_modules/.rts2_cache'),
    tsconfigOverride: {
      compilerOptions: {
        sourceMap: output.sourcemap,
        declaration: shouldEmitDeclarations,
fxy060608's avatar
fxy060608 已提交
91
        declarationMap: false,
fxy060608's avatar
fxy060608 已提交
92
        skipLibCheck: true,
fxy060608's avatar
fxy060608 已提交
93
        ...(buildOption.compilerOptions || {}),
fxy060608's avatar
fxy060608 已提交
94
      },
fxy060608's avatar
fxy060608 已提交
95 96
      exclude: ['**/__tests__', 'test-dts'],
    },
fxy060608's avatar
fxy060608 已提交
97
    useTsconfigDeclarationDir: true,
fxy060608's avatar
fxy060608 已提交
98 99
  })

fxy060608's avatar
fxy060608 已提交
100 101 102 103 104
  // we only need to check TS and generate declarations once for each build.
  // it also seems to run into weird issues when checking multiple times
  // during a single build.
  hasTSChecked = true

fxy060608's avatar
fxy060608 已提交
105
  const external =
fxy060608's avatar
fxy060608 已提交
106
    buildOption.external === false
fxy060608's avatar
fxy060608 已提交
107
      ? []
fxy060608's avatar
fxy060608 已提交
108 109
      : Array.isArray(buildOption.external)
      ? buildOption.external
fxy060608's avatar
fxy060608 已提交
110 111 112 113 114
      : [
          'vue',
          '@vue/shared',
          ...Object.keys(pkg.dependencies || {}),
          ...Object.keys(pkg.peerDependencies || {}),
fxy060608's avatar
fxy060608 已提交
115
          ...(buildOption.external || []),
fxy060608's avatar
fxy060608 已提交
116
        ]
fxy060608's avatar
fxy060608 已提交
117 118 119 120 121
  const plugins = [
    createAliasPlugin(buildOption),
    nodeResolve(),
    commonjs(),
    json({
fxy060608's avatar
fxy060608 已提交
122
      // namedExports: false,
fxy060608's avatar
fxy060608 已提交
123 124 125 126 127
    }),
    tsPlugin,
    createReplacePlugin(buildOption, output.format),
  ]
  if (buildOption.babel) {
fxy060608's avatar
fxy060608 已提交
128
    // TODO weex 使用了 buble 编译,暂时先通过 babel 编译一遍,避免 buble 编译失败
fxy060608's avatar
fxy060608 已提交
129 130
    plugins.push(
      getBabelOutputPlugin({
fxy060608's avatar
fxy060608 已提交
131 132
        allowAllFormats: true,
        sourceType: 'module',
fxy060608's avatar
fxy060608 已提交
133
        presets: [['@babel/preset-env', { targets: ['iOS 10'] }]],
fxy060608's avatar
fxy060608 已提交
134 135 136
      })
    )
  }
fxy060608's avatar
fxy060608 已提交
137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157
  if (buildOption.replaceAfterBundled) {
    const replacements = buildOption.replaceAfterBundled
    plugins.push({
      name: 'replace-after-bundled',
      generateBundle(_options, bundles) {
        Object.keys(bundles).forEach((name) => {
          const bundle = bundles[name]
          if (!bundle.code) {
            return
          }
          Object.keys(replacements).forEach((replacement) => {
            bundle.code = bundle.code.replace(
              new RegExp(replacement, 'g'),
              replacements[replacement]
            )
          })
        })
      },
    })
  }

fxy060608's avatar
fxy060608 已提交
158 159 160
  return {
    input: resolve(entryFile),
    external,
fxy060608's avatar
fxy060608 已提交
161
    plugins,
fxy060608's avatar
fxy060608 已提交
162 163 164 165 166 167
    output,
    onwarn: (msg, warn) => {
      // if (!/Circular/.test(msg)) {
      warn(msg)
      // }
    },
fxy060608's avatar
fxy060608 已提交
168
    treeshake:
fxy060608's avatar
fxy060608 已提交
169
      buildOption.treeshake === false
fxy060608's avatar
fxy060608 已提交
170 171 172 173 174 175 176 177
        ? false
        : {
            moduleSideEffects(id) {
              if (id.endsWith('polyfill.ts')) {
                console.log('[WARN]:sideEffects[' + id + ']')
                return true
              }
              return false
fxy060608's avatar
fxy060608 已提交
178 179
            },
          },
fxy060608's avatar
fxy060608 已提交
180 181 182
  }
}

fxy060608's avatar
fxy060608 已提交
183 184
function createAliasPlugin(buildOption) {
  return alias(buildOption.alias || {})
fxy060608's avatar
fxy060608 已提交
185 186
}

fxy060608's avatar
fxy060608 已提交
187
function createReplacePlugin(buildOption, format) {
fxy060608's avatar
fxy060608 已提交
188
  const replacements = {
fxy060608's avatar
fxy060608 已提交
189 190
    __DEV__: `(process.env.NODE_ENV !== 'production')`,
    __TEST__: false,
fxy060608's avatar
fxy060608 已提交
191
    __NODE_JS__: format === 'cjs',
fxy060608's avatar
fxy060608 已提交
192
  }
fxy060608's avatar
fxy060608 已提交
193 194 195
  // if (process.env.TARGET === 'uni-h5') {
  //   replacements.global = format === 'cjs' ? 'global' : 'window'
  // }
fxy060608's avatar
fxy060608 已提交
196 197
  if (buildOption.replacements) {
    Object.assign(replacements, buildOption.replacements)
fxy060608's avatar
fxy060608 已提交
198 199
  }

fxy060608's avatar
fxy060608 已提交
200
  Object.keys(replacements).forEach((key) => {
fxy060608's avatar
fxy060608 已提交
201 202 203 204
    if (key in process.env) {
      replacements[key] = process.env[key]
    }
  })
205
  return replace({ values: replacements, preventAssignment: true })
fxy060608's avatar
fxy060608 已提交
206
}