解决【create-react-app 使用 styled-jsx】无效问题

  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帮助你自定义[email protected]版本配置
    $ 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. 测试一下,已经可以正常使用啦

其他问题解决

 使用样式组件。不支持嵌套样式。看看https://github.com/zeit/styled-jsx/pull/260 避免这个:

<div>
  <span>
      <style jsx>{...}</style>
  </span>
</div>

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

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

おすすめ

転載: blog.csdn.net/qq_41887214/article/details/120523661