-1

I am working on a Create-React-App project (writing in normal JS (.jsx), not TypeScript for what it's worth).

I wanted to modify some of the build files (swap out some references to local files with live ones) and found the npm package replace-in-file.

I created a .js file for this package and set up the JS for it. The only issue is that when I try to run functions from that file I get the error:

import {replaceInFile} from 'replace-in-file';
SyntaxError: Cannot use import statement outside a module

Not a problem, I just added:

"type": "module",

to my package.json file.

This worked - I no longer get the error above and my script on this file runs.

However, now Create-React-App and Storybook fail to compile and I get the error:

BREAKING CHANGE: The request './my-app' failed to resolve only because it was resolved as fully specified (probably because the origin is strict EcmaScript Module, e. g. a module with javascript mimetype, a '.mjs' file, or a '.js' file where the package.json contains '"type": "module"').

I tried to replace import() with

const replaceInFile = require("replace-in-file");

But that doesn't work of course.

I tried import("replace-in-file"); but that doesn't seem to work with node (eg process.argv fails).

I also tried setting "module": "commonjs" but that still stopped Create-React-App from working.

Would anyone know how I could get both this local file/npm package and Create-React-App working within the 1 project?

1
  • 1
    You could use the file extension .mjs for ES modules. Commented Aug 13, 2024 at 7:27

1 Answer 1

1

Not sure what's going on with your ESM and Commonjs conflicts, but you could try to just write the .js file for "replace-in-file" as a .mjs file (e.g. replace.mjs), and in your CRA project package.json (assuming you want to run this script pre-build):

"scripts": {
    "prebuild": "npx node replace.mjs",
    "build": // e.g. react-scripts build
}

and do not include "type": "module".

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.