uni-app icon indicating copy to clipboard operation
uni-app copied to clipboard

小程序下import的编译问题

Open ziveen opened this issue 1 year ago • 3 comments
trafficstars

环境:

  • vue:3.2.45
  • uni: 3.0.0-alpha-3080220230511001
  • vite: 4.0.3

问题描述: 运行命令yarn dev:mp-weixin后,控制台会报错Charts.Charts is not a constructor.代码片段如下

相关代码

*** lib.js***

function Charts() {
 // do something
}

Charts.prototype.init = function() {}

module.exports = Charts;

pages/index.vue

<template>
     <view></view>
</template>
<script>
import Charts from './lib'
onLoad() {
  const charts = new Charts();
}
</script>

问题处理:

修改lib.js中的导出方式为export default Charts,问题就能正确处理。

分析

这个应该属于uni模块中vite的编译问题,我们项目上一个版本中使用HBUilderx编译无问题。

ziveen avatar Jun 05 '24 04:06 ziveen

你的意思是自定义 js,你使用 cjs 的导出,功能有问题,改为 esm 导出是正常的对吗?你的上一个版本是那个版本,也是 alpha 吗

Otto-J avatar Jun 06 '24 13:06 Otto-J

上一个版本是指的使用Hbuilder运行的项目,现在的使用cli。

ziveen avatar Jun 11 '24 02:06 ziveen

上一个版本是指的使用Hbuilder运行的项目,现在的使用cli。

试下使用@rollup/plugin-commonjs插件配合是否解决

julytian avatar Jun 13 '24 08:06 julytian

2025-02-25 复测了此问题,使用下面代码,在 HBuilderX 工程中可以正常使用。注意 cjs 在 esm 中引用的写法。

<template>
    <view>
        <button >
            加载
        </button>
				
				<view id="main" style="width: 100px;height: 100px;"></view>
    </view>
</template>
<script setup lang="ts">
import { onMounted } from 'vue';
import * as echarts from 'echarts';
onMounted(async ()=>{
	// 基于准备好的dom,初始化echarts实例
	var myChart = echarts.init(document.getElementById('main'));
	// 绘制图表
	myChart.setOption({
	  title: {
	    text: 'ECharts 入门示例'
	  },
	  tooltip: {},
	  xAxis: {
	    data: ['衬衫', '羊毛衫', '雪纺衫', '裤子', '高跟鞋', '袜子']
	  },
	  yAxis: {},
	  series: [
	    {
	      name: '销量',
	      type: 'bar',
	      data: [5, 20, 36, 10, 10, 20]
	    }
	  ]
	});
})

</script>

参考 echat 文档 https://echarts.apache.org/handbook/zh/basics/import

Otto-J avatar Feb 25 '25 03:02 Otto-J