Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

webpack2 中开启 CSS-MODULES #4

Open
gaofant101 opened this issue Jun 28, 2017 · 0 comments
Open

webpack2 中开启 CSS-MODULES #4

gaofant101 opened this issue Jun 28, 2017 · 0 comments

Comments

@gaofant101
Copy link
Owner

gaofant101 commented Jun 28, 2017

开启 CSS-MODULES

CSS少不了要面对命名冲突、模块依赖、全局污染等问题,目前也有不少解决方法;

比如SASS LESS的嵌套写法,VUEscoped关键字都是解决这些问题的;

但是在React项目中CSS-IN-JS这种,要怎么处理CSS一开始很迷糊;

最近看到了CSS-MODULES这个东西,觉得挺有意思;

安利的文章可以看一篇知乎上的专栏:『CSS 模块』 『CSS Modules 详解及 React 中实践

修改配置

开始CSS-MODULES很简单 webpack2中的写法

{
    test: /\.css$/,
    exclude: /node_modules/, //项目中用了`Ant-design`所以得剔除modules
    loaders: [
        'style-loader',
        {
            loader: "css-loader",
+            query: {
+               modules: true,
+                importLoaders: 1,
+                localIdentName: "[name]__[local]__[hash:base64:8]",
+            },
        },
+        {
+            // 写css也需要处理兼容,添加前缀
+            loader: "postcss-loader",
+        },
    ]
},

POSTCSS的配置稍稍有点调整,需要在项目根目录下添加postcss.config.js配置文件;

+const autoprefixer = require('autoprefixer');

+module.exports = {
+    plugins: {
+        autoprefixer: {
+            browsers: ['last 2 versions', 'Firefox ESR', '> 1%', 'ie >= 8', 'iOS >= 8', 'Android >= 4'],
+        }
+    }
+}
题外话

在开始引入autoprefixer的时候发现并没有起作用然后找了很多文档:

webpack2 options are useless #128

Remove Autoprefixer from cssnano #281

大致的问题是之前css-loader里面的cssnano在搞事?编译的时候把autoprefixer添加的前缀给删了.

最终还是看官方配置 postcss/autoprefixer

另一种CSS-IN-JS的解决方案

这是个React的一个第三方库,

官方 styled-components

这个应该是一个更全面的解决方案?跨平台?不是很清楚,RN没有写过,不过语法上,不是很习惯;

import styled from 'styled-components';

const Title = styled.h1`
    font-size: 15px;
    text-align: center;
    color: palevioletred;
`;

// component中用法
<Title>Hello world</Title>

最终编译成了

<h1 data-reactroot class="cItVit">Hello world</h1>

结语

两种解决方案都可行,最终还是看项目需求,和语法习惯了.

@gaofant101 gaofant101 changed the title webpack2中开启CSS-MODULES webpack2 中开启 CSS-MODULES Dec 1, 2017
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant