wxapp-webpack-plugin icon indicating copy to clipboard operation
wxapp-webpack-plugin copied to clipboard

引用微信官方拓展组件webpack报错

Open ludejun opened this issue 3 years ago • 1 comments

wxapp-webpack-plugin 使用最新的0.19.0 在页面中使用官方拓展组件:yarn add @miniprogram-component-plus/tabs .json: { "usingComponents": { "user": "../../components/user/user", "mp-tabs": "@miniprogram-component-plus/tabs" }, "navigationStyle": "custom", "backgroundColor": "#fff" }

打包会报错:TypeError: Cannot read property 'replace' of undefined 我看有几个类似问题,在wxapp-webpack-plugin库中也有

ludejun avatar Mar 28 '21 15:03 ludejun

源码里有这样的逻辑

			if (relativeComponent.indexOf('plugin://') === 0) continue;

所以可以采用如下临时解决方案 1 修改 .json

{
  "usingComponents": {
    "mp-searchbar": "plugin://weui-miniprogram/searchbar/searchbar"
  }
}

2 自定义 json loader

// wx-json-loader.js

import * as _ from 'lodash';

const pluginPrefix = 'plugin://';
export default source => {
  const obj = JSON.parse(source);
  if (!_.isNil(obj.usingComponents) && _.isPlainObject(obj.usingComponents)) {
    _.forEach(obj.usingComponents, value => {
      if (value.indexOf(pluginPrefix) === 0) {
        source = source.replace(value, value.substr(pluginPrefix.length));
      }
    });
  }
  return source;
};

3 配置 webpack,主要代码如下

const ruleJson = {
  test: /\.(json)$/,
  include: /src/,
  use: [relativeFileLoader(), 'wx-json-loader'],
};

return {
  ...
  resolveLoader: {
    alias: {
      'wx-json-loader': resolve('webpack/wx-json-loader.js')
    }
  },
  module: {
   rules: [
     ...,
     ruleJson
  ]
 }
 ...
}

hydra1983 avatar May 06 '21 04:05 hydra1983