简体   繁体   English

用Javascript编译的文件导入CSS而不是CSS

[英]Javascript compiled files to import css instead of scss

I am distributing some compiled files, which means from this tree 我正在分发一些编译文件,这意味着从这棵树

- src
  - components
    - Button
      - index.jsx
      - button.scss

I compiled to this tree: 我编译到这棵树:

- lib
  - components
    - Button
      - index.js
      - button.css

The problem I have is that babel does not change the extension of the required style files to css. 我的问题是babel不会将所需样式文件的扩展名更改为css。 In my Button/index.jsx file I import the style like this: 在我的Button/index.jsx文件中,导入如下样式:

import './button.scss'

This means in my compiled javascript file I still find 这意味着在我编译的javascript文件中,我仍然可以找到

require('./button.scss');

while obviously this file is not present in the new tree, because the extension is now css. 该文件显然不存在于新树中,因为扩展名现在为css。 Is there a babel way to change the imports name/extentions and is this even recommendable? 是否有通俗易懂的方式来更改导入名称/扩展名,这甚至值得推荐吗? At what time of the compilation should this happen? 应该在什么时候进行编译?

Hope you wrote your JSX file like this : 希望您这样编写JSX文件:

src/index.jsx: src / index.jsx:

import styles from './button.scss' or require("./button.scss") 从'./button.scss'或require(“ ./ button.scss”)导入样式

and the transpiled js file under lib 和lib下的已编译js文件

lib/index.js: lib / index.js:

import styles from './button.scss' or require("./button.scss") 从'./button.scss'或require(“ ./ button.scss”)导入样式

and your transpiling those JSX files by using babel cli, is that right ? 然后使用babel cli编译那些JSX文件,对吗?

You can achieve this by following steps: 您可以通过执行以下步骤来实现:

Step 1 : 第1步 :

Include all .scss under main.scss file like below: 在main.scss文件下包括所有.scss,如下所示:

main.scss main.scss

.my-component {  
  @import 'utils/all';
  @import 'base/all';
  @import 'components/all';
}

and placed it as 并放置为

<link rel="stylesheet" href="dist/stylesheets/main.css">

in your html. 在您的html中。 Make a common/global css style guide for all components. 为所有组件制作通用/全局CSS样式指南。

Step 2: 第2步:

if your not intended to use webpack, you can simply place dest css location 如果您不打算使用webpack,则只需放置目标css位置

import styles from './button.css'

in src/JSX itself. 在src / JSX本身中。

Step 3: 第三步:

Using webpack the best way to go about this would probably to use a loader chain such as style!css!sass for your .scss imports which would allow you to simply import and use the styles within your React components in the following manner: 使用webpack进行此操作的最佳方法可能是为.scss导入使用诸如style!css!sass之类的加载程序链,从而使您可以通过以下方式简单地导入和使用React组件中的样式:

import styles from './button.scss';

export default props => <button className={styles.button} />

I'll be ready to adapt if anything better than this approach. 如果有什么比这种方法更好的方法,我将做好适应的准备。

read more at : react-sass-babel-webpack 阅读更多内容: react-sass-babel-webpack

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM