Can I import npm packages dynamically from CDNs in Webpack? - javascript

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';

Related

cannot use import statement outside a module on built exe with electron-forge

I am creating an app with Electron and Vue (using js not ts).
When I run the app using npm run electron:serve the app runs fine.
I now want to build a Windows exe so I can distribute my app. I have tried using electron-builder, electron-packager and electron-forge. Whenever I can get the build to finish, running the exe throws the cannot use import statement outside a module error (referring to the first import statement it finds, i.e. import { app, protocol, BrowserWindow } from 'electron').
I've tried adding "type":"module" to my package.json but (due a bug in Vue, according to this question), that throws Error [ERR_UNSUPPORTED_ESM_URL_SCHEME]
I've also tried changing all my import statements to require but this doesn't work because some of the node modules I'm using use import and the error just throws for those instead.
I'm tearing my hair out over this. Where do I go from here?
UPDATE:
I have found a workaround for the Vue bug and posted my findings on the linked question. I can now add "type":"module" to my package.json.
However, I now get an error thrown when I run npm run electron:serve and from my built exe:
Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: <my_project_root>\dist_electron\index.js
require() of ES modules is not supported.
require() of <my_project_root>\dist_electron\index.js from <my_project_root>\node_modules\electron\dist\resources\default_app.asar\main.js is an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which defines all .js files in that package scope as ES modules.
To be clear, I'm not using require in any of my source code, but the compiled(?) version does?
What's going on here?
UPDATE 2:
As requested, here is a minimal reproducible example that maintains original folder structure, configs and package.json

How can I resolve the following compilation error when running Jest for testing?

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.

Flow: Throws error Cannot resolve module "react-redux" even tho it's installed

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
....

Getting npm packages to work with babel (babel-loader)

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";

Webpack / NPM: Use build version of installed module instead of re-building from source

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';

Categories