rollup.config.js 5.3 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
      },
fxy060608's avatar
fxy060608 已提交
93 94
      exclude: ['**/__tests__', 'test-dts'],
    },
fxy060608's avatar
fxy060608 已提交
95
    useTsconfigDeclarationDir: true,
fxy060608's avatar
fxy060608 已提交
96 97
  })

fxy060608's avatar
fxy060608 已提交
98 99 100 101 102
  // 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 已提交
103
  const external =
fxy060608's avatar
fxy060608 已提交
104
    buildOption.external === false
fxy060608's avatar
fxy060608 已提交
105
      ? []
fxy060608's avatar
fxy060608 已提交
106 107
      : Array.isArray(buildOption.external)
      ? buildOption.external
fxy060608's avatar
fxy060608 已提交
108 109 110 111 112
      : [
          'vue',
          '@vue/shared',
          ...Object.keys(pkg.dependencies || {}),
          ...Object.keys(pkg.peerDependencies || {}),
fxy060608's avatar
fxy060608 已提交
113
          ...(buildOption.external || []),
fxy060608's avatar
fxy060608 已提交
114
        ]
fxy060608's avatar
fxy060608 已提交
115 116 117 118 119 120 121 122 123 124 125
  const plugins = [
    createAliasPlugin(buildOption),
    nodeResolve(),
    commonjs(),
    json({
      namedExports: false,
    }),
    tsPlugin,
    createReplacePlugin(buildOption, output.format),
  ]
  if (buildOption.babel) {
fxy060608's avatar
fxy060608 已提交
126
    // TODO weex 使用了 buble 编译,暂时先通过 babel 编译一遍,避免 buble 编译失败
fxy060608's avatar
fxy060608 已提交
127 128
    plugins.push(
      getBabelOutputPlugin({
fxy060608's avatar
fxy060608 已提交
129 130
        allowAllFormats: true,
        sourceType: 'module',
fxy060608's avatar
fxy060608 已提交
131
        presets: [['@babel/preset-env', { targets: ['iOS 10'] }]],
fxy060608's avatar
fxy060608 已提交
132 133 134
      })
    )
  }
fxy060608's avatar
fxy060608 已提交
135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155
  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 已提交
156 157 158
  return {
    input: resolve(entryFile),
    external,
fxy060608's avatar
fxy060608 已提交
159
    plugins,
fxy060608's avatar
fxy060608 已提交
160 161 162 163 164 165
    output,
    onwarn: (msg, warn) => {
      // if (!/Circular/.test(msg)) {
      warn(msg)
      // }
    },
fxy060608's avatar
fxy060608 已提交
166
    treeshake:
fxy060608's avatar
fxy060608 已提交
167
      buildOption.treeshake === false
fxy060608's avatar
fxy060608 已提交
168 169 170 171 172 173 174 175
        ? false
        : {
            moduleSideEffects(id) {
              if (id.endsWith('polyfill.ts')) {
                console.log('[WARN]:sideEffects[' + id + ']')
                return true
              }
              return false
fxy060608's avatar
fxy060608 已提交
176 177
            },
          },
fxy060608's avatar
fxy060608 已提交
178 179 180
  }
}

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

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

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