未定义包中定义的MeteorJS javascript函数

问题描述 投票:0回答:1

我已经在Meteor中创建了一个自定义包,将javascript添加到了应用程序中。

我的package.js

Package.describe({
    name: 'markel:theme',
    version: '1.0.0',
    summary: 'Theme package',
});

Package.onUse(function(api) {
    // Import all JS files required by the template

    api.addFiles(['assets/js/custom.js']);
});

custom.js中:

function theme_test() {
    console.log('Theme test');
}

当流星将包加载到应用程序中时,它将功能放置在IIFE中。因此,javascript位于(function(){here})中。因此我的函数将返回undefined。

如何定义和使用该功能?

javascript meteor package meteor-blaze
1个回答
0
投票

我希望这些选项之一能解决您的问题,因为我发现很难再现任何undefined值。

选项1-使用模块

虽然您可以通过api.addFiles自动添加文件,但仍然可以选择显式导出文件:

package.js

Package.describe({
    summary: 'Theming',
    version: '1.0.0',
    name: 'marcelweidum:theme',
    git: 'https://github.com/MarcelWeidum/stack-question.git'
});

Package.onUse((api) => {
    api.use('ecmascript') // required to use import/export
    api.addFiles([
        'js/custom.js'
    ], 'client');
    api.mainModule('main.js')
});

package / js / custom.js

export const theme_test = function theme_test () {
    console.log('Here am I!');
}

console.log('Loaded');

package / main.js(在软件包的根文件夹中)

export { theme_test } from './js/custom'

client / main.js

import { theme_test } from 'meteor/marcelweidum:theme'
theme_test()

将在控制台上为您提供:

Loaded
Here am I! 

选项2-使用api.export

您可以使用隐式全局导出主题,可以使用api.export立即访问该主题:

package.jsPackage.describe({摘要:“主题”,版本:“ 1.0.0”,名称:“ marcelweidum:theme”,git:“ https://github.com/MarcelWeidum/stack-question.git”});

Package.onUse((api)=> {api.addFiles(['js / custom.js'],'client');api.export('MyTheme')});


*package/js/custom.js*

function theme_test(){console.log('我在这里!');}

MyTheme = MyTheme || {}MyTheme.theme_test = theme_test

console.log('Loaded');


*client/main.js*
```javascript
MyTheme.theme_test()

将在控制台上为您提供:

Loaded
Here am I! 

选项3-明确导入文件

这将仅在文件导入时将其悬停加载文件内容

package.jsPackage.describe({摘要:“主题”,版本:“ 1.0.0”,名称:“ marcelweidum:theme”,git:“ https://github.com/MarcelWeidum/stack-question.git”})

Package.onUse((api)=> {api.use('ecmascript')})


*js/custom.js* (in root folder of the package)
```javascript
export const theme_test = function theme_test () {
    console.log('Here am I!');
}

console.log('Loaded');

package / js / custom.js

export const theme_test = function theme_test () {
    console.log('Here am I!');
}

console.log('Loaded');

client / main.js

import { theme_test } from 'meteor/marcelweidum:theme/js/custom'
theme_test()

将在控制台上为您提供:

Loaded
Here am I! 

选项4使用bare选项,以防编译器插件使用该文件:

[如果您不希望将文件包装在闭包中,例如,因为它将由自定义compier插件使用,请添加bare选项:

Package.describe({
    summary: 'Theming',
    version: '1.0.0',
    name: 'marcelweidum:theme',
    git: 'https://github.com/MarcelWeidum/stack-question.git'
});

Package.onUse((api) => {
    api.addFiles([
        'js/custom.js'
    ], 'client',  { bare: true });
});

这仍将加载文件,但您必须使用isobuild插件来处理文件。

© www.soinside.com 2019 - 2024. All rights reserved.