Why is Rollup not treeshaking my library? - javascript

I have written an es6 library that compiles to produce the following:
// All the library code, then...
export { default as Campaign } from './modules/campaign.js';
export { default as Triggers } from './modules/triggers.js';
export { default as Asset } from './modules/asset.js';
export { default as AssetSet } from './modules/assetSet.js';
I am then trying to import only Triggers from the library in another project
import { Triggers } from '../../my-library/lib/library.es.js';
When I inspect the bundle it contains all the code for every module exported from my library, rather than just the code from Triggers. I understood that treeshaking would allow me to import just the Triggers code. What am I doing wrong?
My library does not export a default, it only exports the named exports I have written above.
Edit - campaign.js imports asset.js so I would expect to get both when I import Campaign, however Triggers does not reference anything else.

Related

How to properly export/import modules for library usage in javascript

I want to write a javascript library with two files:
snabbpixi.js
export function init() {
}
pixiapi.js
export function createElement() {
}
I want to use this library like this:
import { init } from 'snabbpixi';
import { createElement } from 'snabbpixi/pixiapi';
If I don't do anything and set the package.json for library as:
{
"main": "src/snabbpixi.js"
}
second import doesn't work (import { createElement } from 'snabbpixi/pixiap')
If I compile this library and export as umd format using webpack it also doesn't work.
How can I configure my library so I can import like this:
import { createElement } from 'snabbpixi/pixiap'
I normally do this sort of thing in TypeScript rather than straight JavaScript, but hopefully this works in basically the same way...
Try creating a new file (typically named index.js), with contents like this:
export * from './snabbpixi'; // Adjust paths as needed for your particular case.
export * from './snabbpixi/pixiapi';
Then make index.js your main.
The import you would use would then be flattened-out, however, looking more like:
import { init, createElement } from 'snabbpixi';
When you are using import { Something } from 'somewhere' you are calling on a named export from a given file or directory.
If the two files are in different directories then you can add an index.js file to each directory and then use export { default as function } from './file'
To do this you would have to export the default file from pixiapi and snabbpixi.
If you have both files importing into your index.js then you will still want to export them as defaults. But then you would do the following..
import file1 from './file1'
import file2 from './file2'
export default {
file1,
file2,
}
This will allow you to use the named imports as well and keep them in the same directory

TypeScript declarations for JavaScript module

I recently started using a Node library called bpmn-js (npmjs.com).
It is written in JavaScript, and I'd like to have typings. Thus, I've began reading about d.ts files.
I created this folder structure
webapp
#types
bpmn-js
index.d.ts
With a simple content
declare module 'bpmn-js' {
export class BpmnJS {
constructor();
}
}
But this doesn't seem to work.
"Before" typings, I was able to import the object I needed using
import BpmnJS from 'bpmn-js';
And I was able to instantiate it using
new BpmnJS();
How can I get the typings file to be recognized?
I'm using WebStorm 2019.1.*.
Pretty simple, I was missing export default, or better, the default part.
declare module 'bpmn-js' {
export default class BpmnJS {
constructor(param?: { container: string });
...
}
}
Now this works too
import BpmnJS from 'bpmn-js';

How to import node module in React-Kotlin?

I created an app using the create-react-kotlin-app command and it loads in Chrome fine. I added the React Material UI package via NPM and that was successful. Now how do I use the Material UI module in my component?
Normally with JavaScript, it's a simple import Button from '#material-ui/core/Button' at the top of the component's file, but Kotlin doesn't like that.
How do I translate that line to Kotlin? I am not using Gradle.
I have been struggling with this problem for days now. I came up with the following solution. First we will see multiple ways to declare external modules, then I will show how to use them
.
Consider the following javascript code
import Button from '#material-ui/core/Button' // this means button is exported as default
This will be imported in kotlin in the following ways
Button.kt
#file:JsModule("#material-ui/core/Button")
#file:JsNonModule
package com.mypckage.mykillerapp
import react.Component
import react.RProps
import react.RState
import react.ReactElement
#JsName("default") // because it was exported as default
external val Button : RClass<RProps>
// way 2
#JsName("default")
external class Button : Component<RProps,RState> {
override fun render(): ReactElement?
}
But again, if the statement intend for kotlin has to match the javascript import statement bellow,
import { Button } from "material-ui" // not exported as default
We use the following approach: Button.kt
#file:JsModule("material-ui")
#file:JsNonModule
package com.mypckage.mykillerapp
import react.Component
import react.RProps
import react.RState
import react.ReactElement
// way 1
#JsName("Button") // because it was exported as default
external val Button : RClass<RProps>
// way 2
#JsName("Button")
external class Button : Component<RProps,RState> {
override fun render(): ReactElement?
}
once you have declared on how to use your components, you can just use them as follows:
//way 1:
fun RBuilder.render() {
div {
Button {
attrs.asDynamic().className="submit-button"
+"Submit"
}
}
}
//way 2:
fun RBuilder.render() {
div {
child(Button::class) {
attrs.asDynamic().className="submit-button"
+"Submit"
}
}
}
great. you have imported your component. But until then your are not relying on kotlin type safety and even code completion, to achieve that, you have to go to extra length
as shown bellow
external interface ButtonProps: RProps {
var className : String
var onClick: (Event?)->Unit
var color: String
// . . .
var href: String
}
then go ahead and declare your button as
#JsModule("#material-ui/core/Button")
#JsNonModule
#JsName("default") // because it was exported as default
external val Button : RClass<ButtonProps>
and you can now use it with type safety and code completion as shown bellow
fun RBuilder.render() {
div {
Button {
attrs {
className = "submit-button"
onClick = {
window.alert("Vois La")
}
}
+"Submit"
}
}
}
Hope this helps. Happy coding
EDIT:
There is a community wrapper for material-ui components here
HINT:
Use way 1, as you can see, it is less verbose
The Kotlin way for importing dependencies is close to standard JS importing:
import React from 'react';
export function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
Based on Creating a simple React component with Kotlin.
package hello
import react.*
import react.dom.*
fun RBuilder.hello(name: String) {
h1 {
+"Hello, $name"
}
}
Usually (as Kotlin is Java-based) it uses Gradle tool to handle dependencies:
// part of build.gradle
kotlinFrontend {
// ...
npm {
// ...
dependency("react")
dependency("react-dom")
dependency("react-router")
dependency("react-markdown")
devDependency("css-loader")
devDependency("babel-core")
// ...
}
And are referenced like above:
HomeView.kt:
// https://github.com/Kotlin/kotlin-fullstack-sample/blob/master/frontend/src/org/jetbrains/demo/thinkter/HomeView.kt
import kotlinx.html.*
import org.jetbrains.demo.thinkter.model.*
import react.*
import react.dom.*
import kotlinx.coroutines.experimental.launch
ReactMarkdown.kt:
// https://github.com/Kotlin/kotlin-fullstack-sample/blob/master/frontend/src/org/jetbrains/demo/thinkter/ReactMarkdown.kt
package org.jetbrains.demo.thinkter
import react.*
private val ReactMarkdown: dynamic = runtime.wrappers.require("react-markdown")
Based on: kotlin-fullstack-sample
In create-react-kotlin-app additionally faced the possibility of importing with #JsModule() annotation, while dependencies managing is handled in standard way via package.json:
// src/logo/Logo.kt (outcome of creating new app)
package logo
import react.*
import react.dom.*
import kotlinext.js.*
import kotlinx.html.style
#JsModule("src/logo/react.svg")
external val reactLogo: dynamic
#JsModule("src/logo/kotlin.svg")
external val kotlinLogo: dynamic
And can be also successfully used for JS libraries importing.
Another way would be to use kotlinext.js.*:
// index/index.kt
import kotlinext.js.*
fun main(args: Array<String>) {
requireAll(require.context("src", true, js("/\\.css$/")))
// ...
}
Which provides also require(module: String) function.

ES6 modules: How to automatically re-export all types in the current directory from index.js?

I have lots of code like this scattered around index.js files throughout my React Native project:
import Restaurant from './Restaurant';
import Store from './Store';
import Vineyard from './Vineyard';
import Wine from './Wine';
export {
Restaurant,
Store,
Vineyard,
Wine
};
It's very repetitive and tedious to write out. Is there a way I can automatically re-export all of the other files in the current working directory from index.js? (note I'm also using Flow in my project so any solution should preserve the type information it can infer.)
Thanks.
export * from './Restaurant';
export * from './Store';
By using the above syntax, you can access all exported properties from each component and export them directly.
This is a common pattern when you grouping all Actions in each individual Action file inside index.js and exporting them directly. You can have a look at the github repo
You can also use this pattern if you'd like:
export { default } from './Comp'
export { default as CompHeader } from './CompHeader'
export { default as CompContent } from './CompContent'
// Usage
import Comp, { CompHeader, CompContent } from './component/Comp'

How to get around airbnb eslint import/prefer-default-export rule when using index.js for exports

For cases like this,
/ACollectionOfTinyComponent/index.js
import Container from './Container';
export {
Container,
};
So the index.js becomes a directory to include other small parts without having to write each Component Name out all the time.
So in this case, we can import a component in another component like following:
import {Container} from './ACollectionOfTinyComponent'
//then use Container in the code here
Is this a bad practice? Since if I have airbnb linter enable then I got error linting of
Prefer default export import/prefer-default-export
it asks me to add default but that will cause compile error
I found out that because I added only ONE import & export for the index.js. But if I add more than one its fine!
For example, if I do
import Container from './Container';
import Ezeewei from './Ezeewei';
export {
Container,
Ezeewei,
};
Note that I added one more import of Ezeewei.
Then the linting rule will pass!
it asks me to add default but that will cause compile error
You must be using the wrong syntax for exporting a default.
export { name1 as default, … };
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/export#Syntax
import {Container} ... Is this a bad practice?
Yes. If you have a single entry point into a component (like a a class), you should export it as the default rather than a named export. The designers of the language gave default imports and exports a special syntax to promote it as the primary use case.
http://2ality.com/2014/09/es6-modules-final.html#default-exports-are-favored

Categories

Resources