首页 > 解决方案 > 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?

标签: javascriptnode.jsreactjswebpacknext.js

解决方案


Try and convert the required files to use require and module.exports to import and export respectively

const getImages = () => {
  // return something
};

module.exports =  getImages;


推荐阅读