fastlion-amis
Version:
一种MIS页面生成工具
343 lines (321 loc) • 9.69 kB
JavaScript
// rollup.config.js
import commonjs from '@rollup/plugin-commonjs';
import json from '@rollup/plugin-json';
import resolve from '@rollup/plugin-node-resolve';
import typescript from '@rollup/plugin-typescript';
import license from 'rollup-plugin-license';
import autoExternal from 'rollup-plugin-auto-external';
import {
name,
version,
author,
main,
module,
dependencies
} from './package.json';
import path from 'path';
import svgr from '@svgr/rollup';
import moment from 'moment';
import babel from 'rollup-plugin-babel';
import postcss from 'rollup-plugin-postcss';
import postcssImport from 'postcss-import';
import autoprefixer from 'autoprefixer';
const nodeModulePath = path.resolve(__dirname, 'node_modules');
const settings = {
globals: {},
commonConfig: {
footer: `window.amisVersionInfo={version:'${version}',buildTime:'${moment().format(
'YYYY-MM-DD'
)}'};`
}
};
const external = id => {
const result = new RegExp(
`^(?:${Object.keys(dependencies)
.concat([
'monaco-editor',
'react',
'react-dom',
'rc-input-number',
'@rc-component/mini-decimal',
'@babel/runtime',
'linkify-it',
'react-is',
'markdown-it',
'markdown-it-html5-media',
'mdurl',
'uc.micro',
'react-overlays',
'warning',
'tslib',
'dom-helpers',
'@restart/hooks',
'entities',
'prop-types'
])
.map(value =>
value.replace(/[|\\{}()[\]^$+*?.]/g, '\\$&').replace(/-/g, '\\x2d')
)
.join('|')})`
).test(id);
if (!result && ~id.indexOf('node_modules')) {
console.log(id);
}
return result;
};
const input = [
'./src/index.tsx'
// './src/components/ColorPicker.tsx', // 默认不加载的需要手动维护列表,否则不会编译
// './src/components/BarCode.tsx',
// './src/components/Markdown.tsx',
// './src/components/Tinymce.tsx',
// './src/components/RichText.tsx',
// './src/components/CityDB.ts',
// './src/components/PdfViewer.tsx'
// './src/renderers/Lion/components/PdfViewer/index.tsx'
];
/** 获取子包编译后的入口路径,需要使用相对路径 */
const getCompiledEntryPath = (repo, format) =>
path.join(
'..',
repo,
repo === 'amis-formula' || format === 'cjs' ? 'lib' : 'esm',
'index.js'
);
export default [
// {
// input: './src/index.tsx',
// // input: './scss/themes/cxd.scss',
// input: input.concat([
// // './scss/themes/antd.scss',
// // './scss/themes/ang.scss',
// // './scss/themes/dark.scss',
// // './scss/themes/default.scss',
// './scss/themes/cxd.scss',
// './scss/helper.scss'
// ]),
// output: [
// {
// ...settings,
// // ...settings.commonConfig,
// dir: path.dirname(main),
// format: 'cjs',
// exports: 'named',
// preserveModulesRoot: './src',
// preserveModules: true // Keep directory structure and files
// }
// ],
// external,
// plugins: getPlugins('cjs')
// .concat(
// // 'antd', 'ang', 'dark',
// ['cxd', 'antd', 'ang', 'dark', 'default'].map(theme =>
// postcss({
// include: `**/${theme}.scss`,
// // process: processSass,
// extract: path.resolve(`lib/themes/${theme}.css`),
// plugins: [postcssImport({
// resolve: (id) => {
// if (id.startsWith('~/')) {
// console.log('debug-id', id);
// // 将alias别称~ ,替换为node_modules路径
// return `${nodeModulePath}/${id.slice(2)}`
// }
// return id;
// }
// }), autoprefixer()]
// })
// )
// )
// .concat(
// postcss({
// include: `**/helper.scss`,
// // process: processSass,
// extract: path.resolve(`lib/helper.css`),
// plugins: [postcssImport(), autoprefixer()]
// })
// )
// },
{
input,
output: [
{
...settings,
...settings.commonConfig,
dir: path.dirname(main),
format: 'cjs',
exports: 'named',
preserveModulesRoot: './src',
preserveModules: true // Keep directory structure and files
}
],
external,
plugins: getPlugins('cjs')
}
// {
// // input,
// input: './src/index.tsx',
// output: [
// {
// ...settings,
// ...settings.commonConfig,
// dir: path.dirname(module),
// format: 'esm',
// exports: 'named',
// preserveModulesRoot: './src',
// preserveModules: true // Keep directory structure and files
// }
// ],
// external,
// plugins: getPlugins('esm')
// }
];
function transpileDynamicImportForCJS(options) {
return {
name: 'transpile-dynamic-import-for-cjs',
renderDynamicImport({format, targetModuleId}) {
if (format !== 'cjs') {
return null;
}
return {
left: 'Promise.resolve().then(function() {return new Promise(function(fullfill) {require([',
right:
', "tslib"], function(mod, tslib) {fullfill(tslib.__importStar(mod))})})})'
};
// return {
// left: 'Promise.resolve().then(function() {return new Promise(function(fullfill) {require.ensure([',
// right:
// '], function(r) {fullfill(_interopDefaultLegacy(r("' +
// targetModuleId +
// '")))})})})'
// };
}
};
}
// 参考:https://github.com/theKashey/jsx-compress-loader/blob/master/src/index.js
function transpileReactCreateElement() {
return {
name: 'transpile-react-create-element',
enforce: 'post',
transform: (code, id) => {
if (
/\.(?:tsx|jsx|svg)$/.test(id) &&
code.indexOf('React.createElement') !== -1
) {
const separator = '\n\n;';
const appendText =
`\n` +
`var __react_jsx__ = require('react');\n` +
`var _J$X_ = (__react_jsx__["default"] || __react_jsx__).createElement;\n` +
`var _J$F_ = (__react_jsx__["default"] || __react_jsx__).Fragment;\n`;
const newSource = code
.replace(/React\.createElement\(/g, '_J$X_(')
.replace(/React\.createElement\(/g, '_J$F_(');
code = [appendText, newSource].join(separator);
}
return {
code
};
}
};
}
function getPlugins(format = 'esm') {
const overridePaths = [
// 'amis-formula',
// 'amis-core',
// 'amis-ui',
// 'office-viewer'
].reduce(
(prev, current) => ({
...prev,
[current]: [getCompiledEntryPath(current, format)]
}),
{}
);
const typeScriptOptions = {
typescript: require('typescript'),
sourceMap: false,
outputToFilesystem: true,
// tsconfig: path.resolve(__dirname, 'tsconfig.json'),
...(format === 'esm'
? {
compilerOptions: {
rootDir: './src',
outDir: path.dirname(module)
/** 覆盖继承自顶层tsconfig的paths配置,编译时应该去掉,避免报错@rollup/plugin-typescript TS6305 */
// paths: overridePaths
}
}
: {
compilerOptions: {
rootDir: './src',
outDir: path.dirname(main)
// paths: []
// paths: overridePaths
}
})
};
return [
// svgr({
// svgProps: {
// className: 'icon'
// },
// prettier: false,
// dimensions: false
// }),
// transpileDynamicImportForCJS(),
// autoExternal(),
// json(),
// resolve({
// jsnext: true,
// main: true
// }),
typescript(typeScriptOptions),
// commonjs({
// sourceMap: false
// }),
// format === 'esm'
// ? null
// : babel({
// exclude: 'node_modules/**',
// include: 'src/components/**',
// extensions: ['.jsx', '.tsx', '.js', '.ts'],
// presets: ['@babel/preset-env']
// // plugins: [
// // [
// // 'import',
// // {
// // libraryName: 'amis-ui',
// // libraryDirectory: 'lib',
// // camel2DashComponentName: false,
// // customName: (name, file) => {
// // // if (
// // // ['alert', 'confirm', 'setRenderSchemaFn'].includes(name)
// // // ) {
// // // return `./lib/components/Alert`;
// // // } else if (['toast'].includes(name)) {
// // // return `./lib/components/Toast`;
// // // } else if ('NotFound' === name) {
// // // return `./lib/components/404`;
// // // } else if (['withStore', 'withRemoteConfig'].includes(name)) {
// // // return `./lib/${name}`;
// // // } /* else if (name[0].toUpperCase() === name[0]) {
// // // return `amis-ui/lib/components/${name}`;
// // // }*/
// // return `./src/components/${name}`;
// // }
// // },
// // // 'amis-ui'
// // ]
// // ]
// }),
// format === 'esm' ? null : transpileReactCreateElement(),
license({
banner: `
${name} v${version}
build time: <%=moment().format('YYYY-MM-DD')%>
Copyright 2018<%= moment().format('YYYY') > 2018 ? '-' + moment().format('YYYY') : null %> ${author}
`
})
].filter(item => item);
}