Antd bundle includes both lib and es modules, how to get rid of lib? - create-react-app

As you can see in the bundle analyzer screenshot, our app is using both the es and lib modules from antd (this is when building for production as well as development).
The app was init:ed with CRA and we use craco to override some webpack settings, this is the only thing related to antd that we do in craco.config.js:
plugins: [
{
plugin: CracoAntDesignPlugin,
options: {
customizeTheme: antd_overrides,
},
},
],
We always use the es style import of import { Button } from 'antd'.
Is there a "simple" way to only keep the es modules? Also, I'm guessing tree-shaking isn't happening as we don't actually import 288 modules from antd... but that's a different issue I'm guessing.
I've found this on the subject: https://habr.com/en/company/vk/blog/537880/, but uncertain as to how to go about the things under the hood of CRA (babel for one).
Any help and suggestions greatly appreciated.
Could it potentially be this:
import frFR from 'antd/lib/locale-provider/fr_FR';? As I'm importing from lib? Doesn't seem to be exported as an es module thou.

Related

Importing react-native package when running Vite

I am new to Vite and Vitest. I am experimenting a little bit, trying to add Vitest to a React-native app. I know Vite doesn't really support React Native but I would like to trying running just the tests with Vitest.
I get an error when trying to import React-native modules:
Module .../node_modules/react-native/index.js:14 seems to be an ES Module but shipped in a CommonJS package. You might want to create an issue to the package "react-native" asking them to ship the file in .mjs extension or add "type": "module" in their package.json.
As a temporary workaround you can try to inline the package by updating your config:
// vitest.config.js
export default {
test: {
deps: {
inline: [
"react-native"
]
}
}
}
When adding the suggested config the tests break inside React-native instead, as if the modules in fact is not supported.
What is going on here? Is React-Native only published as commonjs modules, while only esm-modules is supported by Vite? Is there a way around it?
Thanks in advance,
M.

React Native Multiple versions of React (when using hooks)

I've gone through the 3 main causes of the infamous invalid hook call warning, and have determined that I have multiple versions of React in my app. I've confirmed this by this step:
// Add this in node_modules/react-dom/index.js
window.React1 = require('react');
// Add this in your component file
require('react-dom');
window.React2 = require('react');
console.log(window.React1 === window.React2);
Based on my research, I understand that it is probably a dependency I have that is listing react as a dependency instead of a peer dependency, and that there are a few ways to solve this problem. However, I don't know how to figure out which package it is that is causing the issue.
There are lots of solutions online that are relevant to react (such as adding a webpack alias), but unfortunately are not for react-native. I have (perhaps naively) tried to add an alias with module-resolver to babel.config.js, but that did not work:
plugins: [
[
'module-resolver',
{
alias: path.resolve('node_modules/react'),
},
],
]
Figured this out after a long while. The issue was having react-dom library listed as a dependency. I'd read somewhere to do this to support jest testing, but I suppose that advice was dated.
Nonetheless the error was an obvious red herring, so hoping this can help someone out in the future

Bundling a plugin with Rollup but having duplicate Vue.js package imported in the client app's bundle (Nuxt)

Dear Stack Overflow / Vue.js / Rollup community
This could be a noob question for the master plugin developers working with Vue and Rollup. I will write the question very explicitly hoping that it could help other noobs like me in the future.
I have simple plugin that helps with form validation. One of the components in this plugin imports Vue in order to programatically create a component and append to DOM on mount like below:
import Vue from 'vue'
import Notification from './Notification.vue' /* a very simple Vue component */
...
mounted() {
const NotificationClass = Vue.extend(Notification)
const notificationInstance = new NotificationClass({ propsData: { name: 'ABC' } })
notificationInstance.$mount('#something')
}
This works as expected, and this plugin is bundled using Rollup with a config like this:
import vue from 'rollup-plugin-vue'
import babel from 'rollup-plugin-babel'
import { terser } from 'rollup-plugin-terser'
import resolve from 'rollup-plugin-node-resolve'
import commonjs from 'rollup-plugin-commonjs'
export default {
input: 'src/index.js',
output: {
name: 'forms',
globals: {
vue: 'Vue'
}
},
plugins: [
vue(),
babel(),
resolve(),
commonjs(),
terser()
],
external: ['vue']
}
As you can see, Vue.js is getting externalised in this bundle. The aim (and the assumption) is that the client app that imports this plugin will be running on Vue, therefore there's no need to bundle it here (assumption).
The very simple src/index.js that the bundler uses is below:
import Form from './Form.vue'
export default {
install(Vue, _) {
Vue.component('bs-form', Form)
}
}
Rollup creates 2 files (one esm and one umd) and references them in in the plugins package.json file like below:
"name": "bs-forms",
"main": "./dist/umd.js",
"module": "./dist/esm.js",
"files": [
"dist/*"
],
"scripts": {
"build": "npm run build:umd & npm run build:es",
"build:es": "rollup --config rollup.config.js --format es --file dist/esm.js",
"build:umd": "rollup --config rollup.config.js --format umd --file dist/umd.js"
}
Everything works as expected up to this point and the bundles are generated nicely.
The client app (Nuxt SSR) imports this plugin (using npm-link since it's in development) with a very simple import in a plugin file:
/* main.js*/
import Vue from 'vue'
import bsForms from 'bs-forms'
Vue.use(bsForms)
This plugin file (main.js) is added to nuxt.config.js as a plugin:
// Nuxt Plugins
...
plugins: [{src: '~/plugins/main'}]
...
Everything still works as expected but here comes the problem:
Since the clients is a Nuxt app, the Vue is imported by default of course but the externalised Vue module (by the forms plugin) is also imported in the client. Therefore there is a duplication of this package in the client bundle.
I guess the client app can configure its webpack config in order to remove this duplicated module. Perhaps by using something like a Dedupe plugin or something? Can someone suggests how to best handle situation like these?
But what I really want to learn, is the best practice of bundling the plugin at the first place, so that the client doesn't have to change anything in its config and simply imports this plugin and move on.
I know that importing the Vue.js in the plugin may not be a great thing to do at the first place. But there could be other reasons for an import like this as well, for example imagine that the plugin could be written in Typescript and Vue.js / Typescript is written by using Vue.extend statements (see below) which also imports Vue (in order to enable type interface):
import Vue from 'vue'
const Component = Vue.extend({
// type inference enabled
})
So here's the long question. Please masters of Rollup, help me and the community out by suggesting best practice approaches (or your approaches) to handle situations like these.
Thank you!!!!
I had the same problem and I found this answer of #vatson very helpful
Your problem is the combination of "npm link", the nature of nodejs module loading and the vue intolerance to multiple instances from different places.
Short introduction how import in nodejs works. If your script has some kind of library import, then nodejs initially looks in the local node_modules folder, if local node_modules doesn't contain required dependency then nodejs goes to the folder above to find node_modules and your imported dependency there.
You do not need to publish your package on NPM. It is enough if you generate your package locally using npm pack and then install it in your other project npm install /absolute_path_to_your_local_package/your_package_name.tgz. If you update something in your package, you can reinstall it in your other project and everything should work.
Here is the source about the difference between npm pack and npm link https://stackoverflow.com/a/50689049/6072503.
I have sorted this problem with an interesting caveat:
The duplicate Vue package doesn't get imported when the plugin is used via an NPM package (installed by npm install -save <plugin-name> )
However, during development, if you use the package vie npm link (like npm link <plugin-name>) then Vue gets imported twice, like shown in that image in the original question.
People who encounter similar problems in the future, please try to publish and import your package and see if it makes any difference.
Thank you!

webpack-resolve-alias to resolve dependecy's sub-dependency

I'm sort of stuck with one problem and googling it for about three hours brought me nowhere.
Here's the problem. I'm trying to develop my own custom PDF viewer based on PDF.JS lib. Officially it is distributed on npm as pdfjs-dist package. However I need to extend a few classes that are not accessible in pdfjs-dist. So I npm install'ed or yarn add'ed the original repo https://github.com/mozilla/pdf.js.git. This way I have access to classes I need. Inside pdf.js there are core lib that is stored in pdf.js/src/ and a pdf-viewer app that is stored in pdf.js/web/.
Inside that pdf.js/web/ app core lib (pdf.js) is referenced via pdfjs-lib alias that is resolved to pdf.js/src/ during pdf.js inner build process by gulp.
For example pdf.js/web/base_viewer.js:
import { AnnotationLayerBuilder } from './annotation_layer_builder';
import { createPromiseCapability } from 'pdfjs-lib';
import { PDFPageView } from './pdf_page_view';
So now I'm trying to import that pdf.js/web/base_viewer.js in my app that is using latest Webpack 4 (I guess), and this pdfjs-lib sub-dependency is not resolved.
I've tried webpack's resolve-alias mechanism (https://webpack.js.org/configuration/resolve/):
resolve: {
alias: {
'pdfjs-lib': path.resolve(__dirname, './node_modules/pdf.js/src/')
},
}
...but looks like it resolves dependencies only of my own App, but not sub-dependencies of my dependency.
Just in case I'm building Vue 3.0 app using vue-cli and access webpack config this way: https://cli.vuejs.org/guide/webpack.html, but don't think it matters.
Any help from Webpack gurus here?
Thanks.

Is it worth to migrate from Angular 2 to Angular 4?

Hello SO community and Angularians!
So, I am midway developing a huge platform in Angular 2. And I realized that many external libraries and dependencies for Angular 2 are migrating to the new Angular 4. Giving me many errors, obviously.
I could fork these libraries and use the forked versions and subscribe to main library development or, I could just upgrade to Angular 4 my project.
Questions to be answered in order to determinate if it's worth for me to migrate:
Compatibility with Angular 2.4
I have found some adaptations to ensure compatibility with legacy, like this: https://github.com/angular/angular/commit/e99d721
Changes app wide
Do I have to go through my whole app and start fixing things?
I mean, are main functionalities reworked in such way that I will have to review many of them?
Or, are there many build/core incompatibilities that will keep me days occupied fixing compile errors/warnings instead of developing?
I am not asking for someone to do the research for me, I am asking people that maybe already went through this process or simply know well both versions in order to give me some experience tips, clarifications, etc.
At the moment, I am doing my research here:
https://github.com/angular/angular/blob/master/CHANGELOG.md
http://angularjs.blogspot.it/2017/03/angular-400-now-available.html
https://learninglaravel.net/angular-4-new-features-and-improvements
UPDATE
I just migrated to Angular 4. The link that #PierreDuc put in his answer is a very nice tool to have a decent guideline in the migration process.
I would recommend:
Read new features and update yourself with Angular 4. This was specially useful: https://angularjs.blogspot.it/2017/03/angular-400-now-available.html
Follow Angular's guideline and modify your project: https://angular-update-guide.firebaseapp.com/
I would also recommend to commit your current project, create a new branch in your dev repository and proceed with migration in that branch.
An issue that I encountered:
Input, Output and ContentChild will be imported from a wrong path.
My case:
import { Component, OnInit, OnDestro } from '#angular/core';
import { Input, ContentChild } from "#angular/core/src/metadata/directives";
Solution:
import { Component, OnInit, OnDestroy, Input, ContentChild } from '#angular/core';
If you check the changelog there are a couple things you need to keep in mind:
Before updating
Ensure you don't use extends OnInit, or use extends with any lifecycle event. Instead use implements <lifecycle event>.
Stop using DefaultIterableDiffer, KeyValueDiffers#factories, or IterableDiffers#factories
Stop using deep imports, these symbols are now marked with ɵ and are
not part of our public API.
Stop using Renderer.invokeElementMethod as this method has been
removed. There is not currently a replacement.
During the update
Update all of your dependencies to version 4 and the latest typescript.
If you are using Linux/Mac, you can use: npm install
#angular/{animations,common,compiler,compiler-cli,core,forms,http,platform-browser,platform-browser-dynamic,platform-server,router}#4.0.0
typescript#latest --save
If you use animations in your application, you should import
BrowserAnimationsModule from #angular/platform-browser/animations in
your App NgModule.
Replace RootRenderer with RendererFactory2.
Replace Renderer with Renderer2.
After the update
Rename your template tags to ng-template.
Replace OpaqueTokens with InjectionTokens.
If you call DifferFactory.create(...) remove the ChangeDetectorRef
argument.
Replace ngOutletContext with ngTemplateOutletContext.
Replace CollectionChangeRecord with IterableChangeRecord
source
Angular team has announced , let's not call angular 2 or angular 4 let's call it Angular and there will be major update for every 6 months.I have faced the issue in angular v4.0.0 so change the configuration in webpack
new webpack.ContextReplacementPlugin(
// The (\\|\/) piece accounts for path separators in *nix and Windows
/angular(\\|\/)core(\\|\/)#angular/,
helpers.root('./src'), // location of your src
{} // a map of your routes
),
And install #angular/animations package and import in app.module.ts file
import { BrowserAnimationsModule } from '#angular/platform-browser/animations';
#NgModule({
imports: [
BrowserAnimationsModule
]
})
I will prefer to update to latest version of angular. Angular V4.0.0 has reduced the packages weight and they have increased the performance.