簡體   English   中英

如何在Ember.js項目中導入ES2015 JavaScript模塊?

[英]How to import a ES2015 JavaScript module in an Ember.js project?

我想在我的Ember.js項目中使用JavaScript模塊(ES2015),但是它不起作用。

我寫了一個簡單的示例ES6 JavaScript文件,

myES6lib.js

export default function square(b) {
  return b * b;
};

按照管理的要求 ,我跑了

ember generate vendor-shim myES6lib

並在ember-cli-build.js中添加了一行

app.import("vendor/shims/myES6lib.js");

然后我在Ember Controller中調用了平方函數

import MyES6lib from "myES6lib";
...
console.log("Square(5) = " + MyES6lib.square(5));

但我收到如下錯誤消息:

Uncaught TypeError: _myES6lib.default.square is not a function

任何提示表示贊賞,在此先感謝。

注意:我試圖通過Babel將myES6lib轉換為ES5代碼,但是結果是相同的。

您的默認導出是square函數,因此不要像這樣調用它:

console.log("Square(5) = " + MyES6lib.square(5));

您需要這樣稱呼它:

console.log("Square(5) = " + MyES6lib(5));

您的函數看起來更像是一個實用程序函數,將其移動到yourApp/utils/square ,在這種情況下您無需命名該函數,因為它是文件中唯一的函數:

export default function(b) {
  return b * b;
};

然后將其導入您的文件中:

import myCustomSquare from 'myApp/utils/square';

並使用它myCustomSquare(2);

文件中的多種功能:

您將遵循與單個文件相同的邏輯,但在文件中將導出每個函數:

export function square(b) {
  //your logic goes here 
}

export function myOtherCustomFunction(b) {
  //your logic goes here 
}

然后從您的控制器/其他任何地方導入它,如下所示:

import { square, myOtherCustomFunction } from 'myApp/utils/myCustomFunctions'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM