在 create-react-app 中使用 styled-jsx

24 篇文章 5 订阅
20 篇文章 0 订阅
  1. 新建项目,启动
    npx create-react-app my-app
    cd my-app
    npm start
  2. 安装styled-jsx
    npm install --save styled-jsx
    
  3. babelplugins中配置styled-jsx/babe,在根目录文件中创建.babelrc(仅在运行时使用jest test
    {
      "plugins": [
        "styled-jsx/babel"
      ]
    }
    
  4. 使用styled-jsx
    import React from "react";
    
    export default () => {
      return (
        <div className='container'>
          <section className='main'>
            <h1>111111</h1>
          </section>
    
          <style jsx>{`
            .container {
              height: 100vh;
              background: royalblue;
            }
            .main {
              height: 300px;
              background: #61dafb;
            }
          `}</style>
        </div>
      );
    }
    

    可以看到styled-jsx没有起作用

  5. 使用react-app-rewired。它的作用是用来帮助你重写react脚手架配置,使用customize-cra帮助你自定义react-app-rewired@2.x版本配置
    $ yarn add react-app-rewired customize-cra
  6. 在 package.json 中替换
    /* package.json */
    
      "scripts": {
    -   "start": "react-scripts start",
    +   "start": "react-app-rewired start",
    -   "build": "react-scripts build",
    +   "build": "react-app-rewired build",
    -   "test": "react-scripts test",
    +   "test": "react-app-rewired test",
        "eject": "react-scripts eject"
    }
  7. 在根目录下创建 config-overrides.js 
    const { override, addBabelPlugin, addBabelPreset } = require('customize-cra');
    module.exports = override(
        addBabelPlugin('styled-jsx/babel')
    );
    
  8. 在您的index.js(或您将 React 安装到 DOM 的位置)中,在调用 ReactDOM.render(....) 之前,插入以下代码,取自https://github.com/vercel/styled-jsx/issues%20/560#issuecomment-599371026
    const _JSXStyle = require('styled-jsx/style').default;
    if (typeof global !== 'undefined') {
        Object.assign(global, { _JSXStyle });
    }
  9. 不幸的是,如果没有它,这种复杂的配置有点变化无常
  10. 仅当您使用yarn buildyarn test create-react-app 时才需要步骤 3 和 8 
  11. 测试一下,已经可以正常使用啦

欢迎 关注、点赞、评论!━(*`∀´*)ノ亻!

参考文章:style-jsx 样式安装和使用

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

__畫戟__

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值