//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
的数据?
答案 0 :(得分:3)
要首先导入某些内容,您需要将其导出。我希望下面的代码能解决您的问题。
const articles = [
{"title": "title1","content": "content1"},
{"title": "title2","content": "content2"},
{"title": "title3","content": "content3"}]
module.exports = {
articles
}
导出文章常量后,其他文件中的代码应该可以正常工作。
答案 1 :(得分:0)
您应该在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);
答案 2 :(得分:-1)
您需要将商品变量导出为默认导出
//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