【发布时间】:2020-11-16 18:22:08
【问题描述】:
当我的 css 模块与 * as styles 一起导出时,当我捆绑我的代码并在其他 repo 中使用它时变得无法访问时,发生了一件奇怪的事情。
捆绑时样式的响应:
{default: {... my class names} }
当我将代码更改为 import styles from '...' 时,它在捆绑时可以工作,因为样式是默认设置,但测试失败,因为样式无法访问命名的导出。
汇总配置.js
import resolve from '@rollup/plugin-node-resolve'
import commonjs from '@rollup/plugin-commonjs'
import typescript from 'rollup-plugin-typescript2'
import { terser } from 'rollup-plugin-terser'
import postcss from 'rollup-plugin-postcss'
import postCssConfig from '@cinch-labs/postcss-config'
import pkg from './package.json'
import { designTokens, toJSON } from './src/tokens'
const extensions = ['.ts', '.tsx']
// stylelint does work but the postcss one needed to be removed
const postcssPlugins = postCssConfig(toJSON(designTokens)).filter(
({ postcssPlugin }: { postcssPlugin: string }) => postcssPlugin !== 'stylelint',
)
export default [
{
input: './src/index.ts',
output: [
{
file: pkg.main,
format: 'cjs',
},
{
file: pkg.module,
format: 'es',
},
],
plugins: [
postcss({
modules: true,
extract: false,
syntax: 'postcss-scss',
plugins: postcssPlugins,
use: ['sass'],
}),
resolve({
extensions,
}),
commonjs(),
typescript({ tsconfig: 'tsconfig.rollup.json' }),
terser(),
],
external: ['react', 'react-dom'],
},
]
test.component.tsx
import React from 'react'
import classNames from 'classnames'
// I expected the bundler to resolve this for me...
import * as styles from './text.module.scss'
import { TextProps } from './text.types'
export const Text: React.FC<TextProps> = ({
children,
fontSize = 'm',
fontWeight = 'medium',
fontStyle = 'normal',
lineHeight = 'body',
element = 'p',
className,
...props
}) => {
const HtmlEl = element
const classes = classNames(
{
[styles[`textSize${fontSize.toUpperCase()}`]]: fontSize,
[styles[`textWeight${fontWeight.toUpperCase()}`]]: fontWeight,
[styles[`textLineHeight${lineHeight.toUpperCase()}`]]: lineHeight,
[styles[`textFontStyle${fontStyle.toUpperCase()}`]]: fontStyle,
},
className,
)
// classes returns undefined when bundled because of commonjs format.
return (
<HtmlEl className={classes} {...props}>
{children}
</HtmlEl>
)
}
我知道这是由于常见 JS 的工作方式,但是我希望 import * as 样式可以工作。当我将其更改为 import styles from './text.module.scss' 时,它在捆绑时工作正常,但在测试中不起作用。
【问题讨论】:
标签: css reactjs rollup rollupjs css-modules