javascript - Calling React/Webpack module code from Node
问题描述
I have a custom NextJS webpack config where I call a script that gets executed at build-time in the Node runtime (not in the browser):
module.exports = {
webpack: (config, options) => {
if (options.isServer) {
require("./some-script.js")
}
return config
},
}
What the script does doesn't really matter, but I would like to import some code from my React application (that gets executed in the browser, except for SSR, but that's beside the point).
const fs = require("fs");
const getImages = require("../utils/img");
(() => {
// writes something to disk
})();
When I do this I get this error message: SyntaxError: Cannot use import statement outside a module
. This makes sense because I use require for const getImages = require("../utils/img");
but this file is part of the React client-side codebase which uses ES6 import/export modules:
const getImages = () => {
// return something
};
export default getImages;
How can I achieve this? Meaning, how can I call client-side import/export code from a Node.js require script?
解决方案
Try and convert the required files to use require
and module.exports
to import and export respectively
const getImages = () => {
// return something
};
module.exports = getImages;
推荐阅读
- arangodb - 具有顶点邻居条件的 ArangoDB 遍历
- node.js - 如何使用 puppeteer 和 Node js 为 pdf 页面生成屏幕截图
- sql - 如何检查具有不同值但相同类别的列
- java - 读取的文件的位置是什么?
- java - 如何使用jackson(com.fasterxml.jackson)为同一个键消耗不一致的json结构?
- opengl - glGenerateMipmap 在 OpenGL 中是如何工作的?过滤器似乎不起作用
- ios - 对 ShapeLayer 的描边应用渐变?
- c++ - 在具有不兼容代码的 C++ 代码中使用 C 库
- ios - 如何从另一个视图控制器呈现导航控制器的内部?
- php - 在 CodeIgniter 中使用 DOCXTemplate 类时如何修复 var_dump 中的“找不到文件”