[英]EDITED - How to import CSS from 3th party lib - REACT
我在尝试从第3方库导入CSS时卡住了。 一些库除了需要npm install LIB之外,还需要导入css。
安装lib之后,我像这样将css导入我的组件中
import Cards from 'react-credit-cards'
import 'react-credit-cards/lib/styles.scss'
然后使用组件
<Cards
number='XXXX XXXX XXXX XXXX'
name='CARD HOLDER NAME'
expiry='MONTH/YEAR'
cvc='CVV/CVC'/>
第一次运行时,我在导入行中收到错误(找不到模块)。
然后,我更改webpack以在节点模块上加载此文件,如下所示:
{
test: /.css$/,
loader: ExtractTextPlugin.extract('style', 'css?modules&importLoaders=1'),
include: [
>>> /node_modules/, <<<
/flexboxgrid/
]
},
...
}
现在,它不会弹出错误,但是当我运行代码时,不会加载CSS。 我还尝试将css复制并粘贴添加到我的全局css文件中,但仍然无法正常工作。
最后,我的问题= D。 要加载第3方lib CSS,我需要在webpack.config上进行更多设置?
编辑 。
更改我的webpack文件后,现在正在加载CSS。 但是,-看一下下面的图片-通过时CSS认为webpack会生成一些HASH来标识类。 卡组件仍使用原始名称,并且生成的CSS带有此哈希。
卡组件
CSS OF反应信用卡
这是我的webpack.config.json
的加载器部分
const ExtractTextPlugin = require('extract-text-webpack-plugin')
const PATHS = {
app: path.join(__dirname, 'src'),
build: path.join(__dirname, 'build'),
assets: path.join(__dirname, 'assets')
}
const common = {
entry: [
PATHS.app
],
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
include: PATHS.app,
loaders: ['babel']
},
{
test: /.css$/,
loader: ExtractTextPlugin.extract('style', 'css?modules&importLoaders=1'),
include: /flexboxgrid/
},
{
test: /\.scss$/,
loader: ExtractTextPlugin.extract('style', 'css?modules&importLoaders=1!sass?sourceMap'),
exclude: /flexboxgrid/
},
{
test: /\.jpe?g$|\.gif$|\.png$/i,
loader: 'url?name=/imgs/[name].[ext]'
},
{
test: /\.(eot|svg|ttf|woff|woff2)$/,
loader: 'url?name=/fonts/[name].[ext]'
}
]
},
resolve: {
extensions: ['', '.js', '.jsx'],
modulesDirectories: [
'node_modules',
path.resolve(__dirname, './node_modules')
],
packageMains: ['browser', 'web', 'browserify', 'main', 'style']
}
}
...
我假设您正在尝试加载SCSS文件,而不是CSS文件。
您的webpack.config.js
对应部分如下所示:
const ExtractTextPlugin = require('extract-text-webpack-plugin')
module.exports = {
resolve: {
modules: [
path.join(__dirname, 'src'), // to load from your src folder
path.join(__dirname, 'node_modules') // to load from node_modules
]
},
plugins: [
new ExtractTextPlugin('app.css') // extract css and sass files into server.css bundle
],
module: {
rules: [
...
{
test: /\.(s?css|sass)$/, // css, scss and sass will be passed to sass-loader, then css-loader and then to ExtractTextPlugin and css will be extracted to app.css
use: ExtractTextPlugin.extract({
fallback: 'style-loader', // if can't extract css, inline it into JS bundle
use: [
{ loader: 'css-loader', options: {sourceMap: true} },
{ loader: 'sass-loader', options: {sourceMap: true} }
]
})
},
此配置适用于Webpack2,我假设与Webpack3的差异很小。
您正在尝试导入scss而不是css。 您将需要一个sass加载程序。
做,
npm install sass-loader node-sass webpack --save-dev
然后,
将以下加载器添加到您的webpack配置中。
{ test: /\\.scss$/, include: paths.appSrc, loaders: ["style", "css", "sass"] }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.