我正在尝试在我自己的应用程序中为其组件包含另一个库的 css。作为参考,我正在尝试使用此数据表库:https://github.com/filipdanic/spicy-datatable。
在文档中,它指出Out of the box, spicy-datatable is bare-bones. Include this CSS starter file in your project to get the look from the demo. Edit it to suit your needs.
我尝试像这样导入我正在构建的组件顶部的样式表:import * as spicy from 'spicy-datatable/src/sample-styles.css';
在我自己的组件文件中。它没有风格。我尝试将原始代码放入assets/styles
文件夹中的index.scss
文件中 - 不起作用。我尝试将其放在我自己的样式文件中./component.scss
- 不起作用。
我目前将它们设置为:
import * as styles from './component.scss';
import * as spicy from 'spicy-datatable/src/sample-styles.css';
并收到错误:
Module parse failed: Unexpected token (4:0)
You may need an appropriate loader to handle this file type.
webpack.config.js
const dirNode = 'node_modules';
const dirApp = path.join(__dirname, 'client');
const dirAssets = path.join(__dirname, 'assets');
/**
* Webpack Configuration
*/
module.exports = {
entry: {
vendor: ['lodash'],
bundle: path.join(dirApp, 'index')
},
resolve: {
modules: [dirNode, dirApp, dirAssets]
},
plugins: [],
module: {
rules: [
// BABEL
{
test: /.js$/,
loader: 'babel-loader',
exclude: /(node_modules)/,
options: {
compact: true
}
},
// CSS / SASS
{
test: /.(scss)$/,
use: [
'style-loader',
{
loader: 'css-loader',
options: {
importLoaders: 1,
modules: true,
localIdentName: '[path]___[name]__[local]___[hash:base64:5]'
}
},
'sass-loader'
]
},
// IMAGES
{
test: /.(jpe?g|png|gif)$/,
loader: 'file-loader',
options: {
name: '[path][name].[ext]'
}
}
]
}
};
.babelrc
"plugins": [
[
"react-css-modules",
{
"filetypes": {
".scss": {
"syntax": "postcss-scss"
}
},
"webpackHotModuleReloading": true
}
]
我不确定我是否需要添加一些东西来专门处理.css
文件,这是我第一次使用 CSS 模块。我认为 react-css-modules 做到了这一点,所以我不太确定为什么 CSS 文件没有正确加载。
编辑:
编辑了我的网络包以包含CSS:
{
test: /.(css)$/,
use: [
'style-loader',
{
loader: 'css-loader',
options: {
modules: true,
localIdentName: '[path]___[name]__[local]___[hash:base64:5]'
}
}
]
},
错误消失了,但样式仍然没有出现。
你能尝试在下面改变吗:
import * as spicy from 'spicy-datatable/src/sample-styles.css';
自
import from 'spicy-datatable/src/sample-styles.css';
如果您使用的是 CSS 模块,请尝试以下操作:
import spicy from 'spicy-datatable/src/sample-styles.css';
然后在 JSX 元素上使用样式,如下所示:
<h1 className={classes.<className in CSS here>}>
我使用辛辣的数据表库设置了一个代码沙箱并导入了样式,看起来它应用了。样式在"Hello.css"文件中,并在"index.js"中导入。
https://codesandbox.io/s/4j31xj3689
如果库不使用 css-modules(使用className
属性而不是styleName
(,我们需要禁用导入的 css 的模块,因此类名将保持不变。这可以通过两种方式完成:
- 修改您的 Webpack 配置
module: {
rules: [
{
test: /.(css)$/,
use: [
'style-loader',
{
loader: 'css-loader',
options: {
modules: false
}
}
]
},
...
]
}
- 将库 css 直接导入您的 scss 样式表中(感谢这个答案指出了如何执行正确的
.css
导入(。确保从导入行中排除.css
文件扩展名。:global
指令将阻止 CSS 模块修改此指令中所有样式的类名。
:global {
@import "~library-module-name/.../CssFileWithoutExtension";
}