[英]import and export of node.js
//D:/workspace/www/hello-world/src/data/articles.js
const articles = [
{"title": "title1","content": "content1"},
{"title": "title2","content": "content2"},
{"title": "title3","content": "content3"}]
//D:/workspace/www/nodejs_scripts/test.js
import articles from '../hello-world/src/data/articles.js';
console.log(articles);
//D:/workspace/www/nodejs_scripts/package.json
{
"type": "module"
}
運行test.js
D:\workspace\www\nodejs_scripts
λ node -v
v12.11.1
D:\workspace\www\nodejs_scripts
λ node --experimental-modules test.js
(node:7756) ExperimentalWarning: The ESM module loader is experimental.
{}
問題:
如何獲取articles.js
的數據?
為了首先導入某些東西,您需要將其導出。 我希望下面的代碼能解決你的問題。
const articles = [
{"title": "title1","content": "content1"},
{"title": "title2","content": "content2"},
{"title": "title3","content": "content3"}]
module.exports = {
articles
}
導出文章常量后,其他文件中的代碼應該可以正常工作。
您應該在 NodeJS 環境中使用require
而不是import
。 您還需要export
數組:
//D:/workspace/www/hello-world/src/data/articles.js
const articles = [
{"title": "title1","content": "content1"},
{"title": "title2","content": "content2"},
{"title": "title3","content": "content3"}]
module.exports = {
articles
}
然后使用require
:
//D:/workspace/www/nodejs_scripts/test.js
const articles = require('../hello-world/src/data/articles.js');
console.log(articles);
您需要將文章變量導出為默認導出
//D:/workspace/www/hello-world/src/data/articles.js
const articles = [
{"title": "title1","content": "content1"},
{"title": "title2","content": "content2"},
{"title": "title3","content": "content3"}]
export default articles
你可以閱讀更多關於它https://developer.mozilla.org/id/docs/Web/JavaScript/Reference/Statements/export
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.