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

关于引入 Taro-UI 组件遇到的常规问题说明 #1726

Closed
robinv8 opened this issue Dec 19, 2023 · 0 comments
Closed

关于引入 Taro-UI 组件遇到的常规问题说明 #1726

robinv8 opened this issue Dec 19, 2023 · 0 comments

Comments

@robinv8
Copy link
Member

robinv8 commented Dec 19, 2023

使用 Taro UI

常规引入样式

  • 方式 1: 在入口文件中引入 taro-ui 所有的样式

    import 'taro-ui/dist/style/index.scss' 
  • 方式 2:app.scss 样式文件中 import 组件样式并按照文档说明使用

    @import '~taro-ui/dist/style/index.scss'; 

按需引入样式

  • 方式 1: 在页面样式或全局样式中 import 需要的组件样式

    @import '~taro-ui/dist/style/components/button.scss';
  • 方式 2: 通过 babel 插件按需引入组件

    babel-plugin-import 是一款 babel 插件,它会在编译过程中将 import 语句自动转换为按需引入的方式。

    # 安装插件
    npm i babel-plugin-import -D

    在.babelrc 或 babel.config.js 中添加配置:

    {
      "plugins": [
        [
          'import',
          {
            libraryName: 'taro-ui',
            customName: name => `taro-ui/lib/components/${name.slice(3)}`,
            customStyleName: name => `taro-ui/dist/style/components/${name.slice(3)}.scss`
          },
          'taro-ui'
        ]
      ]
    }

    接下来你直接在代码中引入组件而无需引入样式,插件会自动将代码转化为按需引入的形式。

    // 原始代码
    import { AtButton } from 'taro-ui'
    
    // 编译后代码
    import AtButton from 'taro-ui/lib/components/button'
    import 'taro-ui/dist/style/components/button.scss'

注意事项

在 taro3.5 之后的版本中,在开启 prebundle (默认开启)的情况下,会导致 taro-ui 所引用的 @taro/components 组件没有被打进最终的 bundle 中,导致页面表现异常。

为了解决上述问题,可以手动将 taro-ui 排除在 prebundle 列表之外。在 taro 项目的 config/index.js 中新增如下配置项:

module.exports = {
  // ...
  framework: 'react',
- compiler: 'webpack5'
+ compiler: {
+   type: 'webpack5',
+    prebundle: {
+     exclude: ['taro-ui']
+    }
+  },
}

相关 Issues:

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