my-ui
库引用了 ant-design-vue
, 并且按需引入的.
比如 Select
:
import Select from "ant-design-vue/lib/select";
import 'ant-design-vue/lib/select/style/css' // css.js 引用 less 格式
打包后, 上面代码没有变, 由于第三库用了 less ,
这就意味着, 我的库使用者需要在编译时引入 ant 的 less文件.
这就需要对应less文件的打包处理(less-loader), 这很麻烦, 且容易出错.
想要的效果:
我的组件库在打包时, 将引入的 ant 组件和样式"拷贝"过来. 组件编译成js拷贝过来, 样式也是编译成js或css形式拷贝过来.
这样, 我的库使用者, 什么都不用做了. 直接使用就可以了.
这是个很麻烦的问题, 希望大概get到我意思的大神给点思路??
使用 rollup
打包 (node 调用方式)
rollup.rollup(inputOptions)
执行打包逻辑. inputOptions
见下方.
主要打包代码:
const inputOptions = {
input: path.resolve(__dirname, `../packages/${name.split('@yongheui/')[1]}/index.ts`),
plugins: [
nodeResolve(),
css(),
vue({
target: 'browser',
css: false,
}),
// 支持 tsx 解析
babel({
// presets: ["@vue/babel-preset-jsx"],
extensions: [".ts", ".js", ".tsx"],
runtimeHelpers: true,
// exclude: /node_modules/,
exclude: 'node_modules/**',
}),
commonjs(),
typescript({
tsconfigOverride: {
compilerOptions: {
declaration: false,
},
'exclude': [
'node_modules',
'__tests__',
],
},
abortOnError: false,
}),
],
external(id) {
// /*not antd*/
// if ( /^@?ant-design/.test(id) ) { // return false; // }
return /^vue/.test(id)
|| /^@yongheui/.test(id)
|| deps.some(k => new RegExp('^' + k).test(id));
},
}
const getOutFile = () => {
const compName = name.split('@yongheui/')[1]
if(noElPrefixFile.test(name)) {
return `lib/${compName}/index.js`
}
return `lib/y-${compName}/index.js`
}
const outOptions = {
format: 'es',
file: getOutFile(),
paths(id) {
if (/^@yongheui/.test(id)) {
if (noElPrefixFile.test(id)) return id.replace('@yongheui', '..')
return id.replace('@yongheui/', '../y-')
}
},
}
// 执行打包
const bundle = await rollup.rollup(inputOptions)
// 输出
await bundle.write(outOptions)
###将组件样式打包到js文件里即可