构建打字稿前端库

时间:2018-12-13 13:37:14

标签: typescript sass rollupjs css-modules

我想做的是建立一个前端库(React组件和css / scss)。

我在寻找什么

  • 构建单个commonjs .js文件和.css文件。
  • 不要在.js输出中包含库(例如:react等)
  • 允许我使用(s)css模块

我的代码在结构上看起来像这样:

MyComponent.tsx

import { myComponentStyle } from './MyComponent.scss'

export class MyComponent extends React.Component {
  render() {
    return <div className={myComponentStyle} />
  }
}

MyComponent.scss

.myComponentStyle { /* styles */ }

MyComponent.scss.d.ts (由typed-css-modules生成,以使ts编译器满意)

export const myComponentStyle: string;

我有一个index.ts文件,它确实导出了这些文件:

index.ts

export { MyComponent } from './MyComponent.tsx'
// other components

如果我没有样式,则像这样的汇总配置将完全按照我想要的方式构建:

import commonjs from 'rollup-plugin-commonjs'
import typescript from 'rollup-plugin-typescript2'

const pkg = require('./package.json')

export default {
  input: 'src/index.ts',
  output: [{ file: pkg.main, format: 'cjs', sourcemap: true }],
  external: [],
  plugins: [
    typescript({ useTsconfigDeclarationDir: true }),
    commonjs(),
  ],
}

但是我不知道如何处理CSS。我尝试了rollup-plugin-postcssrollup-plugin-postcss-modules,但是都没有编译。

我的问题是:

  • 有没有一种方法(示例)来进行汇总设置?
  • 如果没有其他选择来产生所需的单个.js.css输出(Webpack,无论使用哪种构建系统)?

1 个答案:

答案 0 :(得分:0)

您可以:

有关汇总external here

的更多信息
// rollup.config.js
import commonjs from 'rollup-plugin-commonjs'
import typescript from 'rollup-plugin-typescript2'
import sass from 'rollup-plugin-sass'

const pkg = require('./package.json')

export default {
    input: 'src/index.ts',
    output: [{ file: pkg.main, format: 'cjs', sourcemap: true }],
    external: Object.keys(pkg.dependencies), // OR specify an array: ['react' /* , ...etc */]
    plugins: [
        sass({
            output: 'dist/bundle.css'
        }),
        typescript({ useTsconfigDeclarationDir: true }),
        commonjs(),
    ],
}