I'm really new to webpack, babel, React and all this stuff. So I'm probably missing something really obvious. To get a jumpstart on my React project I'm using react-redux-bootstrap-webpack-starter. It all works well, but now my lack of understanding really shows with my latest problem.
The problem:
I'm trying to import jwtDecode from 'jwt-decode' and it throws the following error:
./src/app/redux/modules/login.js
Module not found: Error: Can't resolve 'jwt-decode/build/jwt-decode' in
'/usr/src/app/src/app/redux/modules'
# ./src/app/redux/modules/login.js 12:17-55
# ./src/app/redux/modules/reducers.js
# ./src/app/redux/store/configureStore.dev.js
# ./src/app/redux/store/configureStore.js
# ./src/app/Root.js
# ./src/app/index.js
# multi react-hot-loader/patch webpack-hot-middleware/client
./src/app/index.js
What have I done:
I've Docker-ized the frontend app, so I just added the jwt-decode package to package.json and rebuilt the image. The Docker build executes npm install.
I've tried to import jwtDecode from 'jwt-decode' then I tried import jwtDecode from 'jwt-decode/build/jwt-decode
I made sure I can reference other npm packages similarly installed. On a new docker instance I installed lodash, imported it in the same file and there was no problem.
My hypotheses:
There's something about the particular jwt-decode package that makes it not work well with babel.
To make it work I need either to modify the jwt-decode package or to configure webpack and the babel-loader differently. How?
Babel doesnt transpile anything for JWT-decode and I dont think webpack has any extra configuration for it either.
It looks like the places that you are trying to use jwt-decode, like: './src/app/redux/modules/login.js ', in your app cannot find the directory and so are failing. Make sure that whatever module loader you're using is referencing the correct path to the jwt-decode directory.
Try loading it like this ( if you are using ES2015 via Babel transpilation):
import jwt_decode from "jwt_decode";
Related
I'm bundling a JS library using Rollup. This lib has a dependency on #tensorflow/tfjs-core.
On tfjs's code, there's a function that fetches a URL. If it's in the browser environment, it uses the global fetch function; if it's not, it tries to import node-fetch.
Something among these lines:
fetch(path: string, requestInits?: RequestInit): Promise<Response> {
if (env().global.fetch != null) {
return env().global.fetch(path, requestInits);
}
if (systemFetch == null) {
systemFetch = require('node-fetch');
}
return systemFetch(path, requestInits);
}
My library is made to run in the browser, so it always uses the global fetch function. However, Rollup still bundles node-fetch's require in my lib's assets.
It should not be an issue, but some consumers are reporting errors when using the library in a React project that uses webpack:
Failed to compile.
./node_modules/[my lib]/index.js
Cannot find module: 'node-fetch'. Make sure this package is installed.
You can install this package by running: npm install node-fetch.
Question is: is there some way I can tell Rollup not no bundle this?
I thought about replacing the require('node-fetch') by undefined after the bundle is generated, but it feels like a dirty hack. Any other sugestions?
PS: I believe marking node-fetch as external on consumer projects would fix the issue, but since I do not use node-fetch in my lib, it would be nice to remove it from final output.
Other package managers can include or exclude files based on the environment, test, development, production, etc.
There is any number of ways of implementing this, even going so far as
# Makefile
ENVIRONMENT ?= test
ROLLUP = $(which rollup)
ENVSUBST = $(which envsubst)
rollup.config.js: src/$(ENVIRONMENT)
${ENVSUBST} < $# > $^
${ROLLUP} $^ -o $(ENVIRONMENT).js
If you created files named after your environments, you could compile them using
make -e environment=browser
I don't expect my code to work, only to express ideas.
There is this loc which is used to exclude node-fetch from the bundle. You could consider a similar approach in your rollup configuration. (I think) If you add that, node-fetch will/should not be a part of your minified library.
I need to require a different version of Zoid npm package dynamically in my JS bundle, depending on a variable. So for example:
if (isLatestVersion) {
zoid = await import('https://unpkg.com/zoid#9.0.80/index.js')
} else {
zoid = await import('https://unpkg.com/zoid#9.0.31/index.js')
}
However when I try the above I get this error:
script.js:2 Uncaught (in promise) Error: Cannot find module 'https://unpkg.com/zoid#9.0.80/index.js'
at webpackMissingModule (script.js:2)
Presumably this is because I don't have zoid defined in my package.json.
So basically my question is, is there's a way to import libraries from a CDN such as unpkg.com or skypack.dev, using Webpack's dynamic imports (aka code splitting)?
The way I ended up solving this was by adding two versions of the same package in my package.json. So I ran these commands:
yarn add zoid9080#npm:zoid#9.0.80
yarn add zoid9031#npm:zoid#9.0.31
yarn remove zoid
Then I imported these two packages statically, since I didn't actually need dynamic importing, and the code ended up being simpler as well:
import zoid from 'zoid9080';
Although I am able to start the npm project using npm start without any issues with webpack or babel, once I run npm test, I find the following error related to testing App.js using App.test.js (where App.js imports ApolloClient):
TypeError: Cannot assign to read only property '__esModule' of object '[object Object]'
| import ApolloClient from 'apollo-boost';
| ^
at node_modules/apollo-boost/lib/bundle.cjs.js:127:74
at Array.forEach (<anonymous>)
at Object.<anonymous> (node_modules/apollo-boost/lib/bundle.cjs.js:127:36)
Essentially, I'm confused as to why I get an error when running the test but not when starting the project.
I've tried adding in a number of babel plugins to both .babelrc and in my webpack config file:
#babel/plugin-transform-object-assign
#babel/plugin-transform-modules-commonjs
babel-plugin-transform-es2015-modules-commonjs
However, I haven't been able to resolve the issue. My thinking was that this is related to the fact that the file that fails to compile was originally CommonJS.
I was only able to find something relatively similar here, https://github.com/ReactTraining/react-router/pull/6758, but I didn't find a solution.
Is there something that I'm missing specifically related to running tests? I should also mention I've tried frameworks other than Jest and ran into the same issue.
EDIT:
I removed everything from App.test.js except the imports to isolate the issue so it just contains the following:
import React from 'react';
import { shallow } from 'enzyme/build';
import App from './App';
UPDATE:
I was able to resolve the initial error by upgrading apollo-boost from version 0.3.1 to 0.4.2. However, I now have a different error that is similarly frustrating. I am using Babel 7 and have added the plugin #babel/plugin-syntax-dynamic-import to both my .babelrc and to my webpack.config.js files. Despite this, I get the following error related to the use of a dynamic import in App.js when running the Jest to test App.test.js:
SyntaxError: Support for the experimental syntax 'dynamicImport' isn't currently enabled
Add #babel/plugin-syntax-dynamic-import (https://git.io/vb4Sv) to the 'plugins' section of your Babel config to enable parsing.
I'm not sure if there is a parsing error or something else, but I've tried numerous things that have not worked. The closest discussion I could find related to this problem is, https://github.com/facebook/jest/issues/5920, however, the proposed solutions don't work for me.
UPDATE:
One thing that I'm trying is to avoid duplication of the babel options as right now they're both in .babelrc and in the babel-loader options within webpack.config.js. From what I found online (Whats the difference when configuring webpack babel-loader vs configuring it within package.json?), the way to make webpack use the settings in .babelrc is to not specify options. However, doing so results in the same error described above showing up only this time when running npm start. I will add that the project that was originally created using create-react-app, however, in order to support multiple pages, I needed to customize webpack's configuration and so ejected from it. I'm not sure why this is so convoluted.
its probably a babel configuration issue, I'm pretty sure jest needs to be compiled to work with create-react-app...
did you specify a setup file in package.json:
"jest": {
"setupFiles": [
"/setupTests.js"
]
}
and in setupTests.js:
import { configure } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
configure({ adapter: new Adapter() });
It turns out that one of the components in the project's src directory had its own local package.json file even though it wasn't being used and was not installed as a local dependency in the top level package.json (instead imports were done using relative urls). For some reason, the existence of this file changed the behavior of webpack and other tools when starting and testing the project such that none of the top level configurations were used for files within directories with separate package.json files. Once I removed these local package.json files from the components sub-directory, all the prior issues were resolved. One hallmark of this problem is that compilation errors were not showing up for JavaScript files that weren't nested under an alternate package.json file.
Hopefully this is useful for anyone that encounters similar errors as I don't think the cause can be directly determined from the compiler messages alone.
Even tho module is installed and it exists, Flow cannot resolve it and throws error.
See below:
1) Inside bash I ran flow and it throws error that module is not found
user#pc:~/code/project$ flow
Error ┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈ src/functionalities/Growth/index.js:3:25
Cannot resolve module react-redux.
1│ // #flow
2│ import React from "react"
3│ import { connect } from "react-redux"
4│
5│ type Props = {
6│ children: Function
Found 1 error
2) Below command checks whether directory exists and it does
user#pc:~/code/project$ ls node_modules | grep react-redux
react-redux
I tried to remove and reinstall both node_modules directory and yarn.lock file.
Versions should be matching:
flow version
Flow, a static type checker for JavaScript, version 0.77.0
.flowconfig:
[version]
0.77.0
This is very likely bug with Flow, I also submitted issue.
How to fix it
You have two options:
stub the dependency by hand
bring in flow-typed to find the dependency type
file/stub it for you
I use option 2 but it is nice to know what is happening underneath
Option 1
In .flowconfig, add a directory under [libs],
...
[libs]
/type-def-libs
...
Now, create that directory at your project root and a file /type-def-libs/react-redux which contains,
declare module 'react-redux' {
declare module.exports: any;
}
Option 2
install flow-typed, if using yarn yarn add -D flow-typed
I prefer to install every locally to the project when possible
run yarn flow-typed install
this will install any type definition files for modules that it finds AND it will stub any modules it doesn't find, which is similar to what we did in option 1
Why is this error happening
Flow is looking for the type definition for the module you are importing. So while the module does exist in /node_modules that module doesn't have a type definition file checked into its code.
I had the same issue as you.
I resolved it by using flow-typed
I did the following:
Install flow-typed globally. example: $ npm install -g flow-typed
Then inside your project root folder, run $ flow-typed install react-redux#5.0.x
• Searching for 1 libdefs...
• flow-typed cache not found, fetching from GitHub...
• Installing 1 libDefs...
• react-redux_v5.x.x.js
└> ./flow-typed/npm/react-redux_v5.x.x.js
react-redux
You should see this if the install was successful.
Then try running flow again $ npm run flow in your project. The error with react-redux will no longer be there.
Alternative solution (for some cases)
Check your .flowconfig and remove <PROJECT_ROOT>/node_modules/.* under the field [ignore] (in case you have it there).
UPDATE 1 (by arka):
Or you can add !<PROJECT_ROOT>/node_modules/react-redux/.* after <PROJECT_ROOT>/node_modules/.*. This will ignore all the modules except for react-redux.
Thanks to #meloseven who solved it here.
I checked my package.json file and noticed react-redux was missing. I manually added it to the dependencies "react-redux": "x.x.x" and ran npm install thereafter. Note that the version number should be compatible with the other modules.
Please ensure that you provide the path under 'ignore' in .flowconfig, like this:
[ignore]
.*/node_modules/react-native/Libraries/.*
and not like this:
.*/node_modules/react-native/Libraries/Components
.*/node_modules/react-native/Libraries/Core
....
I would like to use the dat.GUI library for a project that's build with Webpack 2. If I install the module via npm -install --save-dev dat.gui and then try to import it using import * as DAT from 'dat.gui'; I get the following error when Webpack is trying to compile my project:
ERROR in ./~/dat.gui/src/dat/controllers/NumberControllerSlider.js
Module not found: Error: Can't resolve 'style' in
'/home/me/myProject/node_modules/dat.gui/src/dat/controllers'
BREAKING CHANGE: It's no longer allowed to omit the '-loader' suffix
when using loaders.
I know this error occurs when using Webpack 2 to build Webpack 1 based projects. But why is Webpack even trying to build the module if there already is a build version inside node_modules/dat.gui/build';? Is there a way to tell Webpack or NPM to use the existing build version without trying to re-build it?
When importing a node module, webpack looks into its package.json and uses the main field as entry of the module, similar to what Node.js does (webpack looks for more fields by default, see resolve.mainFields).
Since for dat.gui the main field does not point to the built version but to the source, which actually inlines loaders as seen in dat.gui#0.6.1 - NumberControllerSlider.js for the styleSheet import, and that is not a good idea in general and certainly not to publish.
But you can import the built version by specifying the corresponding path. So your import would be:
import * as DAT from 'dat.gui/build/dat.gui.js';
If you'd like to still import just dat.gui you can configure resolve.alias to point to the built version as follows:
resolve: {
alias: {
'dat.gui': 'dat.gui/build/dat.gui.js'
}
}
With that you can use your original import statement:
import * as DAT from 'dat.gui';