我还不熟悉ECMAScript 6.我刚刚克隆了React Starter Kit repo,它使用ES6作为应用程序代码.我很惊讶地发现linter 配置为禁止出现use strict指令,我认为这是在ES6之前的JavaScript中推荐的.那有什么意义呢?
在Babel 5.x中,我可以编写以下代码:
app.js
export default function (){}
Run Code Online (Sandbox Code Playgroud)
index.js
require('babel/register');
require('./app')();
Run Code Online (Sandbox Code Playgroud)
然后,我可以运行node index.js没有错误.但是,使用Babel 6.x,运行以下代码
index.es6.js
require('babel-core/register');
require('./app')();
Run Code Online (Sandbox Code Playgroud)
导致错误
require(...)不是函数
我想知道为什么?
我一直在通过Webpack教程.在其中一个部分中,它给出了代码示例,其中包含一行本质问题:
export default class Button { /* class code here */ }
Run Code Online (Sandbox Code Playgroud)
在所述教程的下一部分,标题为"代码分割",上面定义的类是按需加载的,如下所示:
require.ensure([], () => {
const Button = require("./Components/Button");
const button = new Button("google.com");
// ...
});
Run Code Online (Sandbox Code Playgroud)
不幸的是,此代码抛出异常:
Uncaught TypeError: Button is not a function
Run Code Online (Sandbox Code Playgroud)
现在,我知道包含ES6模块的正确方法是简单地import Button from './Components/Button';在文件的顶部,但是在文件中的任何其他地方使用类似的构造会让babel成为一个悲伤的熊猫:
SyntaxError: index.js: 'import' and 'export' may only appear at the top level
Run Code Online (Sandbox Code Playgroud)
在require.ensure()上面的上一个()示例的一些摆弄之后,我意识到ES6 export default语法导出一个具有名为property的对象,该对象default包含我的代码(Button函数).
我通过.default在require调用后附加来修复损坏的代码示例,如下所示:
const Button = require("./Components/Button").default;
Run Code Online (Sandbox Code Playgroud)
...但我认为它看起来有点笨拙并且容易出错(我必须知道哪个模块使用ES6语法,哪个使用旧版本module.exports).
这让我 …
我真的很困惑:
export const fooexport default foomodule.exports = foo;我知道这些是非常基本的,但有人可以区分并向我解释这些.我真的很想了解.
我是新人,所以它只是一个问题,我想知道哪一个更有效,哪个给出了最佳的时间复杂性.
第1名
export default class BookingTabs extends Component {
render() {
return (
);
}
}
Run Code Online (Sandbox Code Playgroud)
第2号
class Book extends Component {
render() {
return (
);
}
}
export default Book
Run Code Online (Sandbox Code Playgroud)
问题:
有人可以帮助我理解 Node JS 中 javascript 类/函数导出和 module.exports 之间的区别,以及为什么有两种导出 javascript 属性和函数的方法以及何时使用哪种导出。是否可以同时使用两个导出?
export function getUsers() {
return users
}
Run Code Online (Sandbox Code Playgroud)
VS
module.exports = {
getUsers: function () {
return users
}
}
Run Code Online (Sandbox Code Playgroud) 刚刚开始使用 Shopify,并尝试获得订单。根据 Shopify API 文档,这是我的代码:
const Shopify = require('@shopify/shopify-api');
const client = new Shopify.Clients.Rest('my-store.myshopify.com',
process.env.SHOPIFY_KEY);
module.exports.getShopifyOrderById = async (orderId) => {
return await client.get({
path: `orders/${orderId}`,
});
}
Run Code Online (Sandbox Code Playgroud)
当我执行此代码时,出现以下错误:
TypeError: Cannot read properties of undefined (reading 'Rest')
似乎无法弄清楚问题是什么。
javascript ×6
ecmascript-6 ×3
node.js ×3
commonjs ×2
babeljs ×1
es6-modules ×1
express ×1
reactjs ×1
shopify ×1
shopify-api ×1
shopify-app ×1
strict ×1
webpack ×1