【发布时间】:2020-08-30 08:04:41
【问题描述】:
我设法使用来自 npm 的 this plugin 在我的 Typescript React 类中导入 css 模块。
tsconfig.json
{
"compilerOptions": {
"target": "ESNext",
"outDir": "build",
"jsx": "react",
"noImplicitAny": false,
"removeComments": true,
"sourceMap": false,
"module": "ESNext",
"allowJs": true,
"moduleResolution": "node",
"esModuleInterop": true,
"baseUrl": "src",
"plugins": [{ "name": "typescript-plugin-css-modules" }]
},
"exclude": [
"node_modules/"
],
"include": [
"src/*"
]
}
我还在我的 src/ 文件夹中添加了以下模块文件:
modules.d.ts
declare module '*.module.css' {
const classes: { [key: string]: string };
export default classes;
}
它抑制了所有警告,我能够很好地测试我的代码。我有一个组件可以导入位于同一文件夹中的 css 模块:
- src
- components
- Text.tsx
- Text.module.css
所以我的组件包含以下导入行:
import css from './Text.module.css';
我现在想将我的代码转换为 commonjs 以将其用作其他代码中的 React 模块。这是我的汇总配置:
package.json
"scripts": {
"build": "rollup -c && tsc",
"test": "jest"
}
rollup.config.js
import babel from 'rollup-plugin-babel';
import typescript from 'rollup-plugin-typescript2';
import pkg from './package.json';
import {terser} from 'rollup-plugin-terser';
import autoprefixer from 'autoprefixer';
import postcss from 'rollup-plugin-postcss';
export default [
// CommonJS
{
inlineDynamicImports: true,
input: './src/index.ts',
output: [
{
file: pkg.main,
format: 'cjs'
}
],
external: [
...Object.keys(pkg.dependencies || {})
],
plugins: [
babel({
exclude: 'node_modules/**'
}),
typescript({
typescript: require('typescript')
}),
postcss({
plugins: [autoprefixer()],
sourceMap: true,
extract: true,
minimize: true
}),
terser() // minifies generated bundles
]
}
];
我可以运行yarn build 没有任何错误,但是当我查看构建的代码时,css 模块文件不再位于 Text.js 文件旁边。下面是build生成的文件夹截图:
所有的 css 已经被移到 lib 文件夹,并在生成的 Text.js 文件中:
他们是保留文件结构还是以导入指向正确 css 文件的方式进行转换的方法?
我看到了一些使用 webpack.config.js 的解决方法(运行 eject 脚本),但是我不太容易使用它(因为它为项目添加了很多文件和依赖项,我不确定如何处理好一切)。
非常感谢!
【问题讨论】:
标签: reactjs typescript rollup react-css-modules