creator3d中ts怎么调用js

一个creator3d项目ts编写,添加广告要用以前写的js,ts调js试了很多方法都没成功,要怎么办?

多简单 require 或者 插件脚本

1赞

生成一个对应的.d.ts文件,就行了,类似creator.d.ts

刚开始用,可以说清楚点吗?最好能举个例子。谢谢

当然是… 直接用就好了~

举个栗子

在mian.ts里面使用 niubi.js

文件:niubi.js

export default class niubi{
    shangtian(){
        return "牛逼到上天";
    }
}

文件:mian.ts

import * as niubi from './niubi'  //引入JS
export default class main{
     call_niubi(){
          let niubi = new  niubi(); //使用JS
          niubi.shangtian();
     }
}

如果以前的JS文件,语法比ES5还老,没有模块化

那么就创建个对应的.d.ts文件进行调用即可

大哥可以写比较正常的那种脚本吗?这是我的看着修改下
js文件:
var TestJs = cc.class({
extends: cc.Component,

play(){
    cc.log("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA");
    
}

});
ts文件:
import { _decorator, Component, Node } from “cc”;
const { ccclass, property } = _decorator;

// import TestJS = require(’./TestJs’);
// import {TestJS} from “./TestJS.js”;
import * as TestJS from ‘./TestJs’

@ccclass(“TestTS”)
export class TestTS extends Component {
start () {
let ts = new TestJS();
let s = ts.shangtian();
console.log(s);
// Your initialization goes here.
}
}

这个js你可以修改么,给它加个export

是这样的。

我们最初使用的是 Cocos Creator 开发 2D 游戏,算是积累了一些小的工具类吧。也是最近才开始使用 Creator 3D 开发 3D 游戏。发现 3D 虽然不支持直接创建 js 脚本,但原有 2D 上的 js 脚本依然可以在 3D 下正常运行,就比如这样一个 js 脚本。

var TestJS = cc.Class({
name: “TestJS”,
extends: cc.Component,

start: function () {
    cc.log("start in TestJS...");
},

print: function () {
    cc.log("print from TestJS....");
},

});

// export default TestJS;
// module.exports = TestJS;

所以,我们就想是不是有办法可以让 3D 中使用的 ts 脚本成功调用到原来 2D 下的 js 脚本,这样就可以避免再次开发,可以节省时间了嘛,虽然只是修改。
但我们目前测试类似这样写法的 ts 脚本,都无法调用上述的 js 方法,不论使用上面哪种 export 方式。

import { _decorator, Component, Node, director, systemEvent, CameraComponent } from “cc”;
const { ccclass, property } = _decorator;

import { TestJS } from ("./TestJS");

@ccclass(“TouchTest”)
export class TouchTest extends Component {
/* class member could be defined like this */
// dummy = ‘’;

/* use `property` decorator if your want the member to be serializable */
@property({
    type: TestJS
})
test = null;

start() {
    if(this.test) {
        this.test.print();
    }

}}

在编辑器中就会标红报错,脚本也无法挂载。

其实我们对 Creator 的研究也不久,对 js ts 也都不是很熟悉。希望看到的朋友尽量说的详细一些,谢谢了。
看到有的朋友提到 d.ts,是不是要用这个解决呢?

js 文件:

// TestJS.js

var TestJS = cc.Class({}); 

export { TestJS };

ts 文件:

import { TestJS } from "./TestJS.js";


1赞

测试成功了,感谢大佬~~~

大佬帮忙看看我这个怎么解决呀 版本3.7.1

import xx from “./.js”

按照这个方法引擎报错“ror: Error: Unexpected export statement in CJS module.
” 用的4.7.2引擎基于empty2d开发的项目,想调用Uniapp的sdk

按照这个方法引擎报错“ror: Error: Unexpected export statement in CJS module.

test_demoss.zip (1.4 MB) 大佬 麻烦看看 新建项目也是这样

后来解决了吗

解决了 通过.d.ts方式处理的image
image
使用地方调用
image

还有一个脚本image

你找gpt给你改写成ts脚本