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

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

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

fxy060608's avatar
fxy060608 已提交
186
function createReplacePlugin(buildOption, format) {
fxy060608's avatar
fxy060608 已提交
187
  const replacements = {
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 194
  // if (process.env.TARGET === 'uni-h5') {
  //   replacements.global = format === 'cjs' ? 'global' : 'window'
  // }
fxy060608's avatar
fxy060608 已提交
195 196
  if (buildOption.replacements) {
    Object.assign(replacements, buildOption.replacements)
fxy060608's avatar
fxy060608 已提交
197 198
  }

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