Failed to parse source map - javascript

I created an npm library with rollup. Then, I install and use it in a React project. When i npm start the project it throw me this line:
Failed to parse source map from 'C:\Users\XXXX\Desktop\example\node_modules\#AAA\BBB\src\components\Button\Button.tsx' file:
Error: ENO ENT: no such file or directory, open
'C:\Users\XXXX\Desktop\example\node_modules\#AAA\BBB\src\components\Button\Button.tsx'
This is like a warning more like an error because the button works and webpack says me "No issues found."
In the node_modules folder I have the #AAA/BBB folder with /dist/cjs and /dist/esm.
I dont know what can produce the search in /src in the node modules.
Thank you for your time <3

You can remove the warning by adding GENERATE_SOURCEMAP=false to your .env file
Actually, CRA with Webpack 5.x cause it. They are working on resolving (https://github.com/facebook/create-react-app/pull/11752)

If you want to disable sourcemap locally only, you can disable it inside your local yarn or npm script.
"scripts": {
"start": "GENERATE_SOURCEMAP=false && react-scripts start",
Now, source map is disabled only when you are running the app LOCALLY.

If you do not want to use react-app-rewired, downgrade to react-scripts v4 or set GENERATE_SOURCEMAP=false, you can check out my idea. It is ugly but it works.
Create a script like so:
const { readFileSync, writeFileSync } = require("fs");
const path = "node_modules/source-map-loader/dist/utils.js";
const regex = /.*throw new Error\(`Failed to parse source map from '\${sourceURL}' file: \${error}`\);*/;
const text = readFileSync(path, "utf-8");
const newText = text.replace(regex, `buffer="";sourceURL="";`);
writeFileSync(path, newText, "utf-8");
And then add it to your package.json:
"scripts": {
"start": "node suppress-source-map-warnings.js && react-scripts start"
Using GENERATE_SOURCEMAP=false will make it harder for you to debug your own code so I think this script is a lesser evil.
This code will stop working when source-map-loader changes the error message. But I hope we will a real solution for it by then. Like some kind of flag to suppress warnings when source maps are not found.

delete package-lock.json file
update npm
=> I have tried and succeeded

Related

How to import shared typescript code using create-react-app (no eject)?

I'm trying to achieve TypeScript code sharing in a create-react-app in non-eject mode, but I'm running into the infamous restriction that imports outside of src are not allowed:
You attempted to import ../../common/src/lib.ts which falls outside of the project src/ directory. [...]
For the non-TypeScript case this has been asked & answered here, but I can't get any of the solutions to work with TypeScript. Specifically the issues with the proposed solutions are:
Setting baseDir in ts-config.json: Here create-react-app complains about: Your project's baseUrl can only be set to src or node_modules. Create React App does not support other values at this time.
Approaches based on react-app-rewired: More promising. Disabling the ModuleScopePlugin gets me past the "attempted import outside src" error, but the problem now is that the loader of typescript files doesn't play along:
I have verified that the .ts itself is fine: Copying to ./src and importing it from there works fine.
I have also added ../../common/src folder to the includes list in ts-config.json.
My guess is that somehow the webpack loader configuration has a rule that prevents the TypeScript loader to transpile files that don't match its expected path patterns. How can this be fixed using react-app-rewired?
Symlinking sources doesn't work either -- again with the same problem. Probably because webpack internally resolves the symlinks and sees the file in a path where the normal loader rules don't apply.
Eject based solutions: I'd like not to eject for now, but I tried and I'm basically running into the same problem again.
I've also found other questions that sounded related but didn't answer the problem:
Create React App + Typescript In monorepo code sharing: Sounds basically like the same question, but it is not, because it is asking for the case of an ejected React app.
Sharing code between projects using TypeScript and webpack: Also addresses the code sharing problem, but not create-react-app specific, and I don't know if the solution can be transferred to create-react-app, because it requires manual webpack config control.
Re-using TypeScript typings in a mono repo seems to be a fairly reasonable pattern. Am I missing something or why is the create-react-app making this so difficult?
To reproduce: My code is basically 100% what you get from
npx create-react-app my-app --template typescript
with one import to external added.
You could use craco (create-react-app config override) to override the webpack config (abstracted as part of CRA) without ejecting.
Additionally you could use ts-loader to reference non-transpiled ts code directly in external projects (e.g. if you wanted to reference/use shared code/lib as part of a mono-repo).
Assuming your CRA app is in the client directory your project structure is like the following:
client/
|--src/
|--package.json
shared/
|--package.json
|--(ts files)
package.json
cd client
yarn add -D #craco/craco ts-loader
create a craco.config.js file in the client/ (CRA) directory
ensure the craco.config.js has the following content
const path = require("path");
module.exports = {
webpack: {
configure: webpackConfig => {
// ts-loader is required to reference external typescript projects/files (non-transpiled)
webpackConfig.module.rules.push({
test: /\.tsx?$/,
loader: 'ts-loader',
exclude: /node_modules/,
options: {
transpileOnly: true,
configFile: 'tsconfig.json',
},
})
return webpackConfig;
}
}
};
Replace react-scripts commands in client/package.json with craco
/* client/package.json */
"scripts": {
- "start": "react-scripts start",
+ "start": "craco start",
- "build": "react-scripts build",
+ "build": "craco build"
- "test": "react-scripts test",
+ "test": "craco test"
}
UPDATE: Since react-app-rewired is only maintained passively and doesn't support CRA versions 2+ (we are are three major versions later at the time of writing), I would no longer recommend this approach.
After more hours of experimenting and reading up on GitHub issues, I finally have a working solution. Big thanks to BirukDmitry who made this very helpful post on GitHub. Step-by-step guide:
Install react-app-rewired and customize-cra
npm i react-app-rewired customize-cra --save-dev
Configure react-app-rewird with a minimal config-overrides.js like this:
const { removeModuleScopePlugin, override, babelInclude } = require("customize-cra");
const path = require("path");
module.exports = override(
removeModuleScopePlugin(), // (1)
babelInclude([
path.resolve("src"),
path.resolve("../common/src"), // (2)
])
);
Setting (1) is similar to what is needed for getting around the import-outside-src limitation in general (see linked question).
Setting (2) is crucial though to enabled babel-transpilation (and thus, including TS type stripping I presume) for other paths as well. This is where you have to put add your paths from which you want to import.
No adaptations needed for tsconfig.json.
Import using relative paths, e.g., import * as mymodule from '../../common/src/mymodule'.
#bluenote10 solution did the trick!
There was only one issue in step #2 that prevents Babel from transpilling ts files from ../../common/src
That is modified version of #bluenote10's code (that finally worked for me)
Install react-app-rewired and customize-cra
npm i react-app-rewired customize-cra --save-dev
Configure react-app-rewird with a minimal config-overrides.js like this:
const { removeModuleScopePlugin, override, babelInclude } = require("customize-cra");
const path = require("path");
module.exports = function (config, env) {
return Object.assign( // We need Object.assign() to not to loose initial config
config,
override(
removeModuleScopePlugin(), //1
babelInclude([
path.resolve('src'),
path.resolve('../common/src'), //2
])
)(config, env)
)
}
Setting (1) is similar to what is needed for getting around the import-outside-src limitation in general (see linked question).
Setting (2) is crucial though to enabled babel-transpilation (and thus, including TS type stripping I presume) for other paths as well. This is where you have to put add your paths from which you want to import.
No adaptations needed for tsconfig.json.
Import using relative paths, e.g., import * as mymodule from '../../common/src/mymodule'.
The alias solution for craco or rewired create-react-app is react-app-alias for systems as: craco, react-app-rewired, customize-cra
According docs of mentioned systems replace react-scripts in package.json and configure next:
react-app-rewired
// config-overrides.js
const {aliasWebpack, aliasJest} = require('react-app-alias')
const options = {} // default is empty for most cases
module.exports = aliasWebpack(options)
module.exports.jest = aliasJest(options)
craco
// craco.config.js
const {CracoAliasPlugin} = require('react-app-alias')
module.exports = {
plugins: [
{
plugin: CracoAliasPlugin,
options: {}
}
]
}
all
Configure aliases in json like this:
// tsconfig.paths.json
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"example/*": ["example/src/*"],
"#library/*": ["library/src/*"]
}
}
}
And add this file in extends section of main typescript config file:
// tsconfig.json
{
"extends": "./tsconfig.paths.json",
// ...
}
question where does ../../common/src/mymodule lives at ?
is it another project ?
If it is another project why dont you link'em
inside common code project run npm link
inside the project that will use the common code: npm link common-project
If there are not two different projects. why does it has to be outside of src ?
The link you posted The create-react-app imports restriction outside of src directory
and your case/problem are two totally different thing, plus they be tripping so hard. let me give you and idea of that problem and yours.
As we already know CRA creates a SPA single page app. which means that there is only one single html file. everything happens at the index.html which is located at <project>/public/index.html. If we compile the code we'll notice something the end bundle might look some like this
build
--static
----js
----css
----media
--index.html
--...more hashed crap...
public
src
and by default process.env.PUBLIC_URL is set to "/"
WHAT?? 🤨 yes look let me show you. there is an old say a picture explains more than 1000 words.
if we look at the image that according to its path it is located at ./src/styles/imageSlack.jpg or some.
So what if we console.log it.
WHAAAT!! where they do that at ? one thing you can do to test my theory is if you console.log(process.env.PUBLIC_URL) any where in yow code. now here is the big diference between this and that.
Browsers natively do not know Typescript.
So either you set yow code inside src and we end happy or
follow the separate of concerns principle and we create an npm package with the shared code and just imported as any other module.

vue cli build with target lib: "require is not defined" when component is imported

I'm trying to export a Vue component as a package, and using vue cli to build the dist. I intend to publish it on npm, but I'm currently using a symbolic link for testing purpose. However even with a simple hello-world project I can't make a valid package.
I created a project:
vue create hello-world
Then I modified the package.json:
"scripts": {
"serve": "vue-cli-service serve",
"build": "vue-cli-service build --target lib --name vue-hello-world ./src/components/HelloWorld.vue",
"lint": "vue-cli-service lint"
},
"main": "./dist/vue-hello-world.common.js",
Then I call
npm run build
and it compiles without error.
Then I make an import in a vue component in another project (I used a symbolic link in node_modules):
import HelloWorld from "hello-world";
On page render I get the following error:
[Vue warn]: Failed to resolve async component: function MediaViewerPdf() {
return Promise.all(/*! import() */[__webpack_require__.e(62), __webpack_require__.e(46)]).then(__webpack_require__.bind(null, /*! ./viewers/MediaViewerPdf.vue */ "./vuejs/components/mediaViewer/viewers/MediaViewerPdf.vue"));
}
Reason: ReferenceError: require is not defined
Any idea what's happening?
Remarks:
using vue inspect, I checked that in webpack config that:
target: "web"
I already set resolve.symlinks at false on the importing project.
EDIT: I have confirmed that it doesn't come from the symbolic link, I have exactly the same error with package directly on node_modules.
Repo with whole code: https://github.com/louis-sanna/vue-hello-world
So I asked the question on the vue-cli repo and I got the solution! https://github.com/vuejs/vue-cli/issues/4245
Turns out NODE_ENV was already set at development in my shell, so it was the mode used to make the build.
Just need to set the mode explicitly and it works:
vue-cli-service build --target lib --name vue-hello-world ./src/components/HelloWorld.vue --mode production
You may need to add it to vue.config.js:
config
.mode("production")
This happens due to the fact that Vue CLI Webpack setup by default does not import commonjs modules, as described in your "main" field in package.json. So the problem is with the project that attempts import, not with the project that exports the component.
There are two ways to attempt to solve this problem.
From the importing project side
You can remedy this by installing babel plugins for the project that imports your components and setting babel.config.js
module.exports = {
presets: [
'#vue/app'
],
plugins: [
'#babel/plugin-transform-modules-commonjs', // leave to import .common.js files
'#babel/plugin-transform-modules-umd' // leave to import .umd.js files
]
}
But doing this alone will not be sufficient: you also will need to import CSS that is generated with the library by adding this in your entry file
import 'hello-world/dist/vue-hello-world.css';
Note that I have only tested this using yarn link, but I have confidence that this will work with an imported separate npm module just fine.
From the library side
The intent (I suppose) of the original question - how do I bundle a library so my users don't have to do this little dance each time they want to use it?
Option 1: don't bundle it - provide .vue files and sources. Just include everything in 'src' directory of your module, write a readme with explanation and be done with it. Let the importing project figure the compilation and bundling out.
Option 2: use rollup with Vue plugin to roll components into bundle. There is an example on how to do that. In that example you can see that your project will be able to import .esm build
https://github.com/vuejs/rollup-plugin-vue/tree/master/cookbook/library
Not sure how you are creating the symbolic link, but you should use npm link for that. If you are still having problems (like I did myself) I would suggest you try npm-link-better:
npm install -g npm-link-better
cd vue-hello-world
npm link
cd ../hello-world
nlc -w vue-hello-world
For building component libraries, I suggest you have a look at vue-cli-plugin-component. This plugin already sets up the vue-cli project pretty well.

Npm package how to run script programmatically

I am building a package that uses an external command tool named plop js. In my package.json I want to add a binary that references to an index.js file.
"scripts":{
"plop": "plop"
},
"bin": {
"my-command": "index.js"
},
There is a way to run the plop script from my package in the index.js file?
My goal is to run this script when the user writes my-command in the terminal. (and use the local plop, I want this to be transparent to the consumer)
The reason you can't directly require and use plop is that it is a CLI. As a CLI, it does not export anything but uses process.argv as its input. So all you really need to do is alter process.argv in your script before requireing plop.
process.argv.push('--version');
require('plop');
You could then use the built in --plopfile argument to point to a specific file that you'd like to run.
I just have the same issue and found this code work:
#!/usr/bin/env node
process.argv.push('--plopfile', __dirname + '/plopfile.js');
require('plop');
Since "plop": "^2.7.3",
I found the above not work any more and from https://github.com/plopjs/plop/issues/78
I saw the new solution
#!/usr/bin/env node
const args = process.argv.slice(2);
const {Plop, run} = require('plop');
const argv = require('minimist')(args);
Plop.launch({
cwd: argv.cwd,
configPath: argv.plopfile, // changed to `${process.cwd()}/plopfile.js` in my case
require: argv.require,
completion: argv.completion
}, run);
npm's scripts are (except of start) always being run like npm run plop.
Usually you define a start command which is normally run like npm start and is known by everyone. You can also chain commands there (if you need to run multiple).
Assuming that you want to run plop as first command: If you type npm start, it will execute plop and afterwards node index.js
"scripts":{
"start": "plop && node index.js"
},
If you want to run something just **once* after npm install, put it into "postinstall" : "plop"

Electron require node_modules in main process: Error: Cannot find module ‘linvodb3’

For a angular2/electron learning app I use LinvoDB for persistent data storage based on the angular2-electron-starter seed that comes with two package.json one in root/ one in root/electron. After successful packaging the app.exe throws this error:
A JavaScript error occurred in the main process
Uncaught Exception:
Error: Cannot find module 'linvodb3'
So far I tried:
installing linvodb3 in / and /electron (npm install linvodb3 --save)
installing linvodb3 with --build-from-source
using electron-rebuild in both directories
apm install
multiple deinstallations and
installations of various packages recommended at similar questions.
var LinvoDB = require('linvodb3'); in the according module and main.js
const LinvoDB = require('electron').remote.require('linvodb3');
var LinvoDB = require('linvodb3'); in index.html similar to the jQuery questions.
The only thing I read about and couldn't try was to set the NODE_PATH manually cause I couldn't find a file where it's specified.
As suggested by #JensHabegger the initial problem can be solved by copying the node_modules from the /electron subfolder to /dist, I do this by a script in the /package.json.
The deeper problem of the not found leveldown lib couldn't be fixed with electron-rebuilt but with a postinstall script in /electron/package.json:
"scripts": {
"start": "electron .",
"postinstall": "cd node_modules/leveldown && node-gyp rebuild --target=1.4.8 --arch=x64 --dist-url=https://atom.io/download/atom-shell"
},

Unable to resolve parse-react in React Native project

I'm trying to include parse-react into my React Native project, but when running the app I'm getting the error in XCode and simulator:
Unable to resolve module ./lib/react-native/ParseReact.js from /Users/Corey/Work/example_app/node_modules/parse-react/react-native.js: Unable to find this module in its module map or any of the node_modules directories under /Users/Corey/Work/example_app/node_modules/parse-react/lib/react-native/ParseReact.js and its parent directories
I've included the two packages as such:
import Parse from 'parse/react-native';
import ParseReact from 'parse-react/react-native';
Looking in the node_modules/parse-react folder, the lib directory doesn't contain a react-native directory, but it does have the browser directory. I'm not sure if this is the problem or not, or how I'd go about getting that if it is.
I'm using react 0.14.7, react-native 0.21.0, parse 1.6.14, and parse-react 0.5.1.
I've had the same problem. I'm leaving my package.json here. Install accordingly, and you should be able to include parse modules into your project.
{
"name": "commonDemo",
"version": "0.0.1",
"private": true,
"scripts": {
"start": "node node_modules/react-native/local-cli/cli.js start"
},
"dependencies": {
"parse": "^1.8.1",
"parse-react": "^0.5.0",
"react-native": "^0.20.0"
}
}
Let me know if this works. Ideally, you should be able to include parse modules into your project using latest react-native release. But if using parse is absolutely necessary for your project, use this package.json.
To call Parse.initialize() use this-
var Parse = require('parse/react-native');
To call cloud functions and other functionality, use this-
var ParseReact = require('parse/react-native').Parse;
Look at the parse-react github README page. It says it works with version 1.6.14 of parse. It also says that 1.7 and 1.8 breaks compatibility. I had the same problem and downgrading to 1.6.14 solved the issue.
npm install parse#1.6.14 --save

Categories

Resources