[NervJS/taro]在storybook中使用taro的微信小程序api失效

2024-07-15 867 views
9
相关平台

微信小程序

小程序基础库: 2.15.0 使用框架: React

复现步骤

在storybook初始化后,新建一个单独的storybook,然后写入下面代码,运行storybook

import React from "react";

import Taro from "@tarojs/taro";

export default {
  title: "UI 组件/circle"
};

export const Default = () => {
  console.log(Taro);
  Taro.getSystemInfo().then(res => console.log(res));
};
期望结果

打印出回调信息

实际结果

_tarojs_taroWEBPACK_IMPORTED_MODULE2default.a.getSystemInfo is not a function

环境信息
PS D:\workplace\taro-ks\p> taro info
👽 Taro v3.1.1

  Taro CLI 3.1.1 environment info:
    System:
      OS: Windows 10
    Binaries:
      Node: 14.15.0 - D:\Program Files\nodejs\node.EXE
      npm: 6.14.8 - D:\Program Files\nodejs\npm.CMD

补充信息

不仅如此,大部分微信api都不能调用

回答

4

可否详细介绍一下如何引入,或者可否给一个在storybook中别写taro组件的指导,因为在使用storybook编写正常react应用时很顺畅,但是一编写taro组件的时候就好多问题

7

在 Taro 里面是这样做的:

Webpack 配置 resolve.mainFields:

https://github.com/NervJS/taro/blob/b2c688a5aaf81a3d831b52767a46390cb89c8f8f/packages/taro-webpack-runner/src/config/base.conf.ts#L22

H5 项目引用 @tarojs/taro 时,会解析到 main:h5 指定的入口:

https://github.com/NervJS/taro/blob/b2c688a5aaf81a3d831b52767a46390cb89c8f8f/packages/taro/package.json#L7

最终指向 @tarojs/taro-h5 这个包:

https://github.com/NervJS/taro/blob/b2c688a5aaf81a3d831b52767a46390cb89c8f8f/packages/taro/h5.js#L1-L4

不太清楚 StoryBook 是通过什么方式打包的,你可以按照上述思路去配置咯。

探索成功的话可以给 Taro 写一份配合使用 StoryBook 甚至是在 H5 中使用 @tarojs/components 包的文档哈~

0

不仅仅是@tarojs/taro-h5的指向问题,还有process.env.TARO_ENV等等配置都要改

4

在我的项目加上这些配置能在 storybook 中运行

taro: 3.3.12 storybook: 6.3.12

// .storybook/main.ts
module.exports = {
  // ...,
  webpackFinal: async (baseConfig) => {
    return {
      ...baseConfig,
      resolve: {
        ...baseConfig.resolve,
        alias: {
          ...baseConfig.alias,
          ['@tarojs/components$']: '@tarojs/components/dist-h5/react',
        },
        mainFields: ['main:h5', 'browser', 'module', 'main'],
      },
      plugins: [
        ...baseConfig.plugins,
        new webpack.DefinePlugin({
          // ENABLE_ADJACENT_HTML: JSON.stringify(false),
          ENABLE_CLONE_NODE: JSON.stringify(false),
          ENABLE_INNER_HTML: JSON.stringify(false),
          ENABLE_SIZE_APIS: JSON.stringify(false),
          ENABLE_TEMPLATE_CONTENT: JSON.stringify(false),
        }),
      ],
    };
  },
  // ...
}
// .storybook/preview.tsx
import { DecoratorFn } from '@storybook/react';

import '@tarojs/components/dist/taro-components/taro-components.css';
import { defineCustomElements, applyPolyfills } from '@tarojs/components/loader';

export const decorators: DecoratorFn[] = [
  (Story) => {
    applyPolyfills().then(function () {
      defineCustomElements(window);
    });

    return <Story />;
  },
];
2

ModuleBuildError: Module build failed (from ./node_modules/babel-loader/lib/index.js): SyntaxError: D:\Documents\ProjectName\ .storybook\preview.ts: Unexpected token, expected "," (24:18) 22 | }); 23 | 24 | return < Story / >; | ------------^ 25 | }, 26 | ];

我的环境: taro版本:3.3.15; storybook版本: 6.3.12;

2

.storybook/preview.ts 文件后缀改成 .tsx

0

.storybook/preview.ts 文件后缀改成 .tsx

非常感谢 @linhaobin !上述问题已经解决,但又遇到一堆新的编译问题,都是webpack处理taro代码的问题,可能在storybook里预览taro组件还是太困难了。不知道可以放弃组件预览,只显示注释文档的内容吗?或许我该换用一个更单纯的React文档库吧。

ERROR in ./node_modules/@tarojs/taro-h5/src/api/createAnimation/index.js 10:9
Module parse failed: Unexpected token (10:9)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See 
https://webpack.js.org/concepts#loaders
|   }
|
>   $style = null
|   sheet = null
|   appendStyleSheet = () => {
3

请教@linhaobin 我按你的示例配置了storybook,现在有个问题是,运行yarn storybook后,发现如果调用Taro.pxTransform(size)的话,转换的值仍旧是rpx单位,rocess.env.TARO_ENV已经显示是h5环境。这个问题如何解决?

Screen Shot 2022-01-18 at 10 57 26 AM
8

@ZakaryCode 我的.storybook/main.js配置如下:

const path = require('path');

module.exports = {
  babel: options => ({
    ...options,
    plugins: [
      [require('babel-plugin-transform-taroapi').default, {
        apis: require(require.resolve('@tarojs/taro-h5/dist/taroApis', { basedir: path.resolve(__dirname, '..') })),
        packageName: '@tarojs/taro'
      }],
    ]
  }),
  webpackFinal: config => ({
    ...config,
    resolve: {
      ...config.resolve,
      mainFields: ['main:h5', 'browser', 'module', 'jsnext:main', 'main'],
      alias: {
        ...config.resolve.alias,
        '@tarojs/taro': '@tarojs/taro-h5'
      },
    },
  }),
  reactOptions: {
    fastRefresh: true,
  },
  "stories": [
    "../src/components/**/*.stories.tsx"
  ],
  "addons": [
    "@storybook/addon-links",
    "@storybook/addon-essentials"
  ],
  "framework": "@storybook/react",
  features: {
    babelModeV7: true,
  },
}

运行yarn storybook 后浏览器中报如下错误:

Unexpected error while loading ./IconGroup.stories.tsx: ENABLE_INNER_HTML is not defined
 ReferenceError: ENABLE_INNER_HTML is not defined
    at TaroNodeImpl.bind (http://localhost:6006/vendors~main.iframe.bundle.js:16066:9)
    at new TaroNode (http://localhost:6006/vendors~main.iframe.bundle.js:13937:14)
    at new TaroElement (http://localhost:6006/vendors~main.iframe.bundle.js:14615:9)
    at new TaroDocument (http://localhost:6006/vendors~main.iframe.bundle.js:16147:9)
    at _createInstance (http://localhost:6006/vendors~main.iframe.bundle.js:44169:12)
    at resolveInstance (http://localhost:6006/vendors~main.iframe.bundle.js:44189:18)
    at http://localhost:6006/vendors~main.iframe.bundle.js:44289:104
    at resolve (http://localhost:6006/vendors~main.iframe.bundle.js:44313:12)
    at http://localhost:6006/vendors~main.iframe.bundle.js:43288:102
    at Container.push../node_modules/inversify/es/container/container.js.Container._get (http://localhost:6006/vendors~main.iframe.bundle.js:43279:44)
error @ index.js:56
(anonymous) @ executeLoadable.js:57
(anonymous) @ executeLoadable.js:51
executeLoadable @ executeLoadable.js:50
executeLoadableForChanges @ executeLoadable.js:99
getProjectAnnotations @ start.js:123
(anonymous) @ index.js:217
_runResolutions @ index.js:214
then @ index.js:67
getProjectAnnotationsOrRenderError @ PreviewWeb.js:140
initialize @ PreviewWeb.js:118
configure @ start.js:148
configure @ index.js:21
(anonymous) @ generated-stories-entry.js:6
./generated-stories-entry.js @ generated-stories-entry.js:6
__webpack_require__ @ bootstrap:853
fn @ bootstrap:150
0 @ storybook-init-framework-entry.js:1
__webpack_require__ @ bootstrap:853
checkDeferredModules @ bootstrap:45
webpackJsonpCallback @ bootstrap:32
(anonymous) @ main.iframe.bundle.js:1
index.js:56 Unable to load story 'icongroup--default':
error @ index.js:56
renderStoryLoadingException @ PreviewWeb.js:1374
_callee3$ @ PreviewWeb.js:322
tryCatch @ runtime.js:63
invoke @ runtime.js:294
(anonymous) @ runtime.js:119
asyncGeneratorStep @ PreviewWeb.js:8
_next @ PreviewWeb.js:10
(anonymous) @ PreviewWeb.js:10
(anonymous) @ PreviewWeb.js:10
selectSpecifiedStory @ PreviewWeb.js:348
(anonymous) @ PreviewWeb.js:288
(anonymous) @ index.js:217
_runResolutions @ index.js:214
then @ index.js:67
initializeWithStoryIndex @ PreviewWeb.js:281
(anonymous) @ PreviewWeb.js:178
(anonymous) @ index.js:217
_runResolutions @ index.js:214
then @ index.js:67
initializeWithProjectAnnotations @ PreviewWeb.js:177
(anonymous) @ PreviewWeb.js:119
(anonymous) @ index.js:217
_runResolutions @ index.js:214
then @ index.js:67
initialize @ PreviewWeb.js:118
configure @ start.js:148
configure @ index.js:21
(anonymous) @ generated-stories-entry.js:6
./generated-stories-entry.js @ generated-stories-entry.js:6
__webpack_require__ @ bootstrap:853
fn @ bootstrap:150
0 @ storybook-init-framework-entry.js:1
__webpack_require__ @ bootstrap:853
checkDeferredModules @ bootstrap:45
webpackJsonpCallback @ bootstrap:32
(anonymous) @ main.iframe.bundle.js:1
Show 7 more frames
index.js:56 Error: Couldn't find story matching 'icongroup--default'.
- Are you sure a story with that id exists?
- Please check your stories field of your main.js config.
- Also check the browser console and terminal for error messages.
    at PreviewWeb._callee3$ (PreviewWeb.js:322:1)
    at tryCatch (runtime.js:63:1)
    at Generator.invoke [as _invoke] (runtime.js:294:1)
    at Generator.next (runtime.js:119:1)
    at asyncGeneratorStep (PreviewWeb.js:8:1)
    at _next (PreviewWeb.js:10:1)
    at PreviewWeb.js:10:1
    at new Promise (<anonymous>)
    at PreviewWeb.<anonymous> (PreviewWeb.js:10:1)
    at PreviewWeb.selectSpecifiedStory (PreviewWeb.js:348:1)
0

@ZakaryCode 结合 @linhaobin 的设置,更新了文档,现在用到taro组件的storybook不会报错,并且在storybook的preview.js中加载了Taro component的样式,并且执行initPxTransform方法。

9

initPxTransform是做了些什么 rpx转成px吗?有您的仓库例子吗

1

我看文档了设置了initPxTransform没有啥变化

0

rpx 转 px 需要配置 postcss-pxtransform