Import npm packages - rollupjs

How should I import npm packages? If I just add lodash bundling goes from 6ms to 900ms!?
Is there no way to cache static dependencies?
If I add lodash to external, globals and customResolveOptions in rollup.config.js it is excluded from the bundle. But how could I add it in a libs.js file for example?
Here are my files:
app.js
import _ from 'lodash'
alert(_.concat(["hi", "hello"]))
rollup.config.js
import resolve from 'rollup-plugin-node-resolve';
import commonjs from 'rollup-plugin-commonjs';
import uglify from 'rollup-plugin-uglify';
import babel from 'rollup-plugin-babel';
const production = !process.env.ROLLUP_WATCH;
export default {
input: 'src/index.js',
output: {
file: 'scripts/bundle.js',
format: 'iife',
sourcemap: true
},
plugins: [
resolve(),
commonjs(),
babel({
exclude: 'node_modules/**'
}),
production && uglify()
]
};
package.json
{
"devDependencies": {
"npm-run-all": "^4.1.2",
"rollup": "^0.55.5",
"rollup-plugin-commonjs": "^8.0.2",
"rollup-plugin-node-resolve": "^3.0.0",
"rollup-plugin-uglify": "^3.0.0",
"babel-core": "^6.26.3",
"babel-plugin-external-helpers": "^6.22.0",
"babel-preset-env": "^1.7.0",
"rollup-plugin-babel": "^3.0.4"
},
"dependencies": {
"lodash": "^4.17.10"
},
"scripts": {
"build": "rollup -c",
"watch": "rollup -c -w",
"dev": "npm-run-all --parallel watch"
},
...
}

You can manually separate the entrypoints for "libs" and source code to speed up your build:
rollup.config.js
import resolve from 'rollup-plugin-node-resolve';
import commonjs from 'rollup-plugin-commonjs';
import uglify from 'rollup-plugin-uglify';
import babel from 'rollup-plugin-babel';
const production = !process.env.ROLLUP_WATCH;
export default [{
input: 'src/index.js',
output: {
file: 'scripts/bundle.js',
format: 'iife',
sourcemap: true,
globals: {
'lodash': '_',
},
},
external: ['lodash'],
plugins: [
babel(),
production && uglify()
]
}, {
input: 'src/common.js',
output: {
file: 'scripts/common.js',
format: 'umd',
name: 'window',
extend: true,
sourcemap: true
},
plugins: [
resolve(),
commonjs(),
production && uglify()
]
}];
common.js
export { default as _ } from 'lodash'
It does add the overhead of maintaining the common.js file with libraries. Personally, I find it gives the best control over file size and compile time. If you're constantly installing and including new npm packages, this will be be hard to maintain.

Related

how to integrate ngx-logger into playwright

I'm new in TS & angular. Now I have a legacy playwright project, which I'd like to use ngx-logger for logging.
According to many ngx-logger tutorials, I know there might be 3 steps to integrate:
install ngx-logger
npm install --save ngx-logger
import the library in the root module, i.e., app.module.ts
import { LoggerModule, NgxLoggerLevel } from 'ngx-logger';
import LoggerModule.forRoot in your application module. This is where we can configure the logger:
#NgModule({
imports: [
BrowserModule,
HttpClientModule,
LoggerModule.forRoot({
serverLoggingUrl: 'http://localhost:4201/', // Replace with YOUR API
level: NgxLoggerLevel.TRACE,
serverLogLevel: NgxLoggerLevel.ERROR,
disableConsoleLogging: false
})
],
declarations: [AppComponent],
bootstrap: [AppComponent]
})
export class AppModule { }
So finally, we can start logging anywhere in the application:
export class AppComponent {
constructor(private logger: NGXLogger) {
this.logger.debug("Debug message");
this.logger.info("Info message");
this.logger.log("Default log message");
this.logger.warn("Warning message");
this.logger.error("Error message");
}
}
However, I'm stuck in step 2&3, because I don't know where to setup these in a playwright project.
In my playwright project, I only have config files like:
~/playwright.config.ts
~/src/config/launch.config.ts
~/src/config/testrunner.config.ts
none of them contains #NgModule I could inject the codes.
Can anyone give me some hints with how to proceed?
Thank in advance.
package.json
{
"name": "portal-test",
"version": "0.0.0",
"private": true,
"description": "Portal Test Automation Suite",
"homepage": "./",
"dependencies": {
"dotenv": "^16.0.0",
"eml-parser": "^1.0.6",
"expect-playwright": "^0.7.1",
"moment": "^2.29.4",
"ngx-logger": "^5.0.11",
"npm": "^7.19.1",
"path": "^0.12.7",
"pdf.js-extract": "^0.1.5",
"pdfreader": "^1.2.11",
"playwright-core": "^1.15.2",
"request-promise": "^4.2.6",
"ts-node": "^10.3.0",
"typescript": "^4.4.3",
"yarn": "^1.22.10"
},
"scripts": {
"compile": "npx tsc --incremental -p tsconfig.json",
"test": "CI_TEST_ENV=uat npx playwright test --config=src/config/testrunner.config.ts --headed",
"test-local": "CI_TEST_ENV=local npx playwright test --config=src/config/testrunner.config.ts --headed",
"test-local-headless": "CI_TEST_ENV=local npx playwright test --config=src/config/testrunner.config.ts",
"test-dev": "CI_TEST_ENV=dev npx playwright test --config=src/config/testrunner.config.ts --headed",
"test-uat": "CI_TEST_ENV=uat npx playwright test --config=src/config/testrunner.config.ts --headed"
},
"devDependencies": {
"#playwright/test": "^1.28.1",
"playwright": "^1.15.2"
},
"extends": []
}

Solidjs library rollup configuration: unresolved dependencies

I try to build a solidjs npm lib using rollup to provide some components. I intend to build esm and cjs module using the following rollup.config.js:
import commonjs from "rollup-plugin-commonjs";
import typescript from "rollup-plugin-typescript2";
import babel from "#rollup/plugin-babel";
import postcss from "postcss";
import nodeResolve from "#rollup/plugin-node-resolve";
export default {
input: "./src/index.ts",
output: [
{
file: "dist/index.cjs.js",
format: "cjs",
},
{
file: "dist/index.esm.js",
format: "esm",
},
],
external: [
"#suid",
"#suid/icons-material",
"#suid/material",
"solid-js",
"solid-js/web",
],
plugins: [
nodeResolve(),
resolve(),
commonjs(),
postcss({
autoModules: true,
plugins: [],
sourceMap: true,
extract: true,
minimize: true,
}),
typescript(),
babel({
babelHelpers: "bundled",
exclude: "node_modules/**",
extensions: [".ts", ".tsx"],
}),
],
};
Unfortunately, i cannot build this. Here's the error message:
(!) Unresolved dependencies
https://rollupjs.org/guide/en/#warning-treating-module-as-external-dependency
~/MonthPicker.module.css (imported by "src/MonthPicker.tsx")
~/DatePicker.module.css (imported by "src/DatePicker.tsx")
#suid/icons-material/ExpandLess (imported by "src/MonthPicker.tsx")
#suid/icons-material/ExpandMore (imported by "src/MonthPicker.tsx")
created dist/index.cjs.js, dist/index.esm.js in 849ms
If I understood correctly, nodeResolve() is supposed to help here, but i guess i have misconfigured it.
EDITS:
added postcss as #snnsnn proposed
removed babel from this post (it seems this is a rollup issue)
You are missing postCss plugin.
https://www.npmjs.com/package/rollup-plugin-postcss
Edit:
You are missing some peer dependencies like postcss, #babel/core and I believe that is why you receive "unresolved dependencies" error. I installed them as dev dependencies, but it is better if you add them as peerDependencies:
{
"dependencies": {
"#suid/icons-material": "^0.5.1",
"#suid/material": "^0.8.0",
"babel-plugin-react-css-modules": "^5.2.6",
"rollup-plugin-postcss": "^4.0.2",
"rollup-plugin-postcss-modules": "^2.1.1",
"solid-js": "^1.6.9",
"suid": "^1.0.0"
},
"devDependencies": {
"#babel/core": "^7.20.12",
"#rollup/plugin-babel": "^6.0.3",
"#rollup/plugin-node-resolve": "^15.0.1",
"#suid/vite-plugin": "^0.1.0",
"#types/node": "^18.11.18",
"#typescript-eslint/eslint-plugin": "^5.48.1",
"#typescript-eslint/parser": "^5.48.0",
"eslint": "^8.31.0",
"eslint-config-airbnb-base": "^15.0.0",
"eslint-config-airbnb-typescript": "^17.0.0",
"eslint-config-prettier": "^8.6.0",
"eslint-plugin-import": "^2.27.5",
"eslint-plugin-prettier": "^4.2.1",
"eslint-plugin-solid": "^0.9.1",
"postcss": "^8.4.21",
"prettier": "^2.8.2",
"rollup": "^3.10.0",
"rollup-plugin-commonjs": "^10.1.0",
"rollup-plugin-node-resolve": "^5.2.0",
"rollup-plugin-typescript2": "^0.34.1",
"typescript": "^4.8.2",
"vite": "^4.0.4",
"vite-plugin-solid": "^2.5.0"
}
}
Used following rollup.config.js:
import commonjs from "rollup-plugin-commonjs";
import resolve from "rollup-plugin-node-resolve";
import typescript from "rollup-plugin-typescript2";
import babel from "#rollup/plugin-babel";
import nodeResolve from "#rollup/plugin-node-resolve";
import postcss from 'rollup-plugin-postcss-modules';
export default {
input: "./src/index.tsx",
output: [
{
file: "dist/index.cjs.js",
format: "cjs",
},
{
file: "dist/index.esm.js",
format: "esm",
},
],
external: [
"#suid",
"#suid/icons-material",
"#suid/material",
"solid-js",
"solid-js/web",
],
plugins: [
nodeResolve(),
resolve(),
commonjs(),
postcss({
autoModules: true,
plugins: [],
sourceMap: true,
extract: true,
minimize: true,
}),
typescript(),
babel({
babelHelpers: "bundled",
exclude: "node_modules/**",
extensions: [".ts", ".tsx"],
}),
],
};
Used a simple application as index.tsx:
import { render } from 'solid-js/web';
import style from './app.module.css';
export const App = () => {
const handleClick = () => {
console.log('Clicking');
};
return (
<div class={style.app}>
App! <button onClick={handleClick}>Some Button</button>
</div>
);
};
render(App, document.body);
Your project compiles:
pnpm run build
> #edelmeier/solid-timeline#0.0.1 build **snipped**/solid-timeline
> rollup -c
./src/index.tsx → dist/index.cjs.js, dist/index.esm.js...
created dist/index.cjs.js, dist/index.esm.js in 1.6s

Rollup Error in pnpm-workspace monorepo:'default' is not exported by ../../node_modules/.pnpm/classnames#2.3.1/node_modules/classnames/index.js

I have a UI lib repo , which could working well with below rollup config
My rollup.conf.js
import babel from '#rollup/plugin-babel';
import commonjs from '#rollup/plugin-commonjs';
import json from '#rollup/plugin-json';
import postcss from 'rollup-plugin-postcss';
import { nodeResolve } from '#rollup/plugin-node-resolve';
import { terser } from 'rollup-plugin-terser';
import typescript from 'rollup-plugin-typescript2';
import { DEFAULT_EXTENSIONS } from '#babel/core';
const isProd = process.env.NODE_ENV === 'production';
const pkg = require('./package.json');
const dependencies = Object.keys(pkg.peerDependencies);
export default {
input: './components/index.ts',
output: [
{
format: 'umd',
name: pkg.name,
file: 'lib/index.main.js',
globals: {
antd: 'antd',
'antd-mobile': 'antd-mobile',
react: 'react',
'react-dom': 'react-dom',
'styled-components': 'styled-components',
},
},
{
format: 'es',
name: pkg.name,
file: 'lib/index.module.js',
globals: {
antd: 'antd',
'antd-mobile': 'antd-mobile',
react: 'react',
'react-dom': 'react-dom',
'styled-components': 'styled-components',
},
},
],
onwarn: function (warning) {
if (warning.code === 'CIRCULAR_DEPENDENCY') {
return;
}
if ( warning.code === 'THIS_IS_UNDEFINED' ) { return; };
console.error(`(!) ${warning.message}`);
},
plugins: [
typescript({
include: ['*.ts+(|x)', '**/*.ts+(|x)'],
exclude: 'node_modules/**',
typescript: require('typescript'),
}),
babel({
exclude: 'node_modules/**',
babelHelpers: 'runtime',
extensions: [...DEFAULT_EXTENSIONS, '.ts', 'tsx'],
}),
nodeResolve({
mainField: ['jsnext:main', 'browser', 'module', 'main'],
browser: true,
}),
commonjs(),
json(),
postcss({
// Minimize CSS, boolean or options for cssnano.
minimize: isProd,
// Enable sourceMap.
sourceMap: !isProd,
// This plugin will process files ending with these extensions and the extensions supported by custom loaders.
extensions: ['.less', '.css'],
use: [['less', { javascriptEnabled: true, modifyVars: { '#primary-color': '#42b983' } }]],
}),
isProd && terser(),
],
external: dependencies,
};
however , when i am using pnpm workspace and try to manage it inside , below error showing:
The Error I'm getting and don't know to solve
[!] Error: 'default' is not exported by ../../node_modules/.pnpm/classnames#2.3.1/node_modules/classnames/index.js, imported by ../../node_modules/.pnpm/antd#4.16.13_react-dom#16.13.1+react#16.13.1/node_modules/antd/es/empty/index.js
https://rollupjs.org/guide/en/#error-name-is-not-exported-by-module
../../node_modules/.pnpm/antd#4.16.13_react-dom#16.13.1+react#16.13.1/node_modules/antd/es/empty/index.js (18:7)
16:
17: import * as React from 'react';
18: import classNames from 'classnames';
^
19: import { ConfigContext } from '../config-provider';
20: import LocaleReceiver from '../locale-provider/LocaleReceiver';
Error: 'default' is not exported by ../../node_modules/.pnpm/classnames#2.3.1/node_modules/classnames/index.js, imported by ../../node_modules/.pnpm/antd#4.16.13_react-dom#16.13.1+react#16.13.1/node_modules/antd/es/empty/index.js
at error (/Users/yejinlei/Documents/playground/personal/pnpm-workspace/node_modules/.pnpm/rollup#2.57.0/node_modules/rollup/dist/shared/rollup.js:158:30)
at Module.error (/Users/yejinlei/Documents/playground/personal/pnpm-workspace/node_modules/.pnpm/rollup#2.57.0/node_modules/rollup/dist/shared/rollup.js:12339:16)
at Module.traceVariable (/Users/yejinlei/Documents/playground/personal/pnpm-workspace/node_modules/.pnpm/rollup#2.57.0/node_modules/rollup/dist/shared/rollup.js:12724:29)
at ModuleScope.findVariable (/Users/yejinlei/Documents/playground/personal/pnpm-workspace/node_modules/.pnpm/rollup#2.57.0/node_modules/rollup/dist/shared/rollup.js:11517:39)
 ELIFECYCLE  Command failed with exit code 1.
the https://rollupjs.org/guide/en/#error-name-is-not-exported-by-module page does not really help, since the namedExports has been no longer working.
"#babel/core": "^7.12.9",
"#rollup/plugin-babel": "^5.2.2",
"#rollup/plugin-commonjs": "^17.0.0",
"#rollup/plugin-json": "^4.1.0",
"#rollup/plugin-node-resolve": "^11.0.0",
"rimraf": "3.0.2",
"rollup-plugin-postcss": "^4.0.1",
"rollup-plugin-terser": "^7.0.2",
"rollup-plugin-typescript2": "^0.30.0",
"tslib": "^2.0.3",
"typescript": "^4.1.2"
its a lib repo that integrated with antd. antd-mobile, which currently using React for UI development.
Try regex in rollup.config.js under plugins:
babel({
babelHelpers: "bundled",
exclude: /node_modules/, // add this
}),

ng-bootstrap AoT build failure with Unexpected Token and missing loader

I am trying to use ng-bootstrap library in my project. Runs fine with webpackdevserver and jit build but aot build throw errors similar to following
Module parse failed: E:\SVNCode\Learning\spa\aot\node_modules\#ng-
bootstrap\ng-bootstrap\alert\alert.ngfactory.ts Unexpected token (13:21)
You may need an appropriate loader to handle this file type.
I have searched for the issue but the only reference related to ng-bootstrap was ticket no. #1381 on github, which was closed without any further details. So, I believe that I may be missing something very small. Here are relevant details
Node : 8.1.3
Angular & Compiler-cli: 4.2.4
Webpack : 2.6.1
typescript : 2.3.4
ng-bootstrap : 1.0.0-alpha.26
bootstrap : 4.0.0-alpha.6 (using CDN but tried after install also with
same result)
webpack.prod.js
let ExtractTextPlugin = require('extract-text-webpack-plugin');
let webpack = require('webpack');
let HtmlWebpackPlugin = require('html-webpack-plugin');
let CompressionPlugin = require("compression-webpack-plugin");
let CopyWebpackPlugin = require('copy-webpack-plugin');
let path = require('path');
let rootDir = path.resolve(__dirname, '..');
module.exports = {
entry: {
'polyfills': './spa/polyfills.ts',
'vendor': './spa/vendor-aot.ts',
'app': './spa/main-aot.ts' // AoT compilation
},
output: {
path: path.join(rootDir,'wwwroot'),
filename: 'js/[name]-[hash:6].bundle.js',
chunkFilename: 'js/[id]-[hash:6].chunk.js',
publicPath: '/'
},
resolve: {
extensions: ['.ts', '.js', '.json', '.css', '.html']
},
module: {
rules: [
{
test: /\.ts$/,
use: [
'babel-loader?presets[]=es2015',
'awesome-typescript-loader?configFileName=tsconfig-aot.json',
'angular-router-loader?aot=true&genDir=spa/aot/'
],
exclude: /node_modules/
},
{
test: /\.css$/,
loaders: ['to-string-loader', 'css-loader']
},
{
test: /\.html$/,
use: 'html-loader'
}
],
exprContextCritical: false
},
plugins: [
new webpack.optimize.CommonsChunkPlugin({
name: ['app', 'vendor', 'polyfills']
}),
new webpack.LoaderOptionsPlugin({
minimize: true,
debug: false
}),
new webpack.optimize.UglifyJsPlugin({
beautify: false,
compress: {
warnings: false
},
output: {
comments: false
},
sourceMap: false,
mangle: {keep_fnames: true}
}),
new CompressionPlugin({
asset: "[path].gz[query]",
algorithm: "gzip",
test: /\.js$|\.html$/,
threshold: 10240,
minRatio: 0.8
}),
new ExtractTextPlugin("[name].css"),
new HtmlWebpackPlugin({
template: './spa/index.html'
}),
new CopyWebpackPlugin([
{ from: path.join(rootDir,'spa','assets'), to: 'assets'}
]),
new webpack.NoEmitOnErrorsPlugin()
]
};
tsconfig-aot.js
{
"compilerOptions": {
"target": "es2015",
"module": "commonjs",
"moduleResolution": "node",
"sourceMap": false,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"removeComments": true,
"noImplicitAny": true,
"suppressImplicitAnyIndexErrors": true,
"lib": ["es2015","dom"],
"typeRoots": ["node_modules/#types"],
"types":["node", "core-js"]
},
"files": [
"spa/app/app.module.ts",
"spa/main-aot.ts"
],
"exclude": ["node_modules"],
"angularCompilerOptions": {
"genDir": "spa/aot",
"skipMetadataEmit": true
},
"awesomeTypescriptLoaderOptions":{
"useWebpackText": true,
"useCache": true
}
}
vendor-aot.ts
import '#angular/platform-browser';
import '#angular/core';
import '#angular/common';
import '#angular/http';
import '#angular/forms';
import '#angular/router';
import '#angular/platform-browser/animations';
import 'rxjs';
//can import others e.g. bootstrap, jquery etc
//can import js, ts, css, sass etc..
import '#ng-bootstrap/ng-bootstrap';
Thanks & Regards
After searching the internet high and low, going through several stackoverflow posts and github project configurations/samples, I finally managed to fix it (duct tape way).
All I had to do to fix the issue was remove the exclusion of node_modules folder in webpack config file.
Now, WHY exclusion of node_modules works for angular and rxjs packages but not for ng-bootstrap, is still beyond me.
Exclusion works when building for jit but for aot to succeed node_modules HAS TO BE INCLUDED in ts loader chain. Now the build time for aot has increased multifold, but at least it works.

Compile/Export sass with webpack 2

I've used Grunt and Gulp before so webpack is a bit new to me still.
Now I've configured webpack to successfully bundle my javascript perfectly. The issue I'm having now is bundling my sass and outputting the result to a file.
My understanding is that I have to use extract-text-webpack-plugin to extract the styles to its own file rather in inlining in <head>, but I'm not sure on this part. I'm looking to do the following for sass:
Compile the contents of src/main/stylesheets/**/*.scss
Output the contents to a single file app/assets/stylesheets/bundle.css
I know I can achieve this using gulp/grunt easily, but I'm trying to learn how webpack does things. My webpack.config.babel.js is as follows:
import path from "path";
import ExtractTextPlugin from "extract-text-webpack-plugin";
export default {
entry: {
index: path.join(__dirname, "src/main/javascripts/application.js")
},
output: {
path: path.join(__dirname, "app/assets/javascripts/"),
publicPath: "/assets/",
filename: "bundle.js"
},
module: {
rules: [
{
test: /\.scss$/,
include: path.join(__dirname, "src/main/stylesheets/"),
loader: ExtractTextPlugin.extract({
fallback: "style-loader",
use: [
{
loader: "css-loader",
query: { modules: false, sourceMaps: true }
},
{
loader: "sass-loader",
query: { sourceMaps: true }
}
]
})
},
{
test: /\.js$/,
include: path.join(__dirname, "src/main/javascripts/"),
exclude: /node_modules/,
use: [
{ loader: "babel-loader" }
],
}
]
},
plugins: [
new ExtractTextPlugin(path.join(__dirname, "app/assets/stylesheets/bundle.css"))
]
}
Dependencies from package.json if that matters:
"dependencies": {
"bootstrap-sass": "^3.3.7",
"jquery": "^3.1.1"
},
"devDependencies": {
"babel-core": "^6.23.1",
"babel-loader": "^6.3.1",
"babel-preset-env": "^1.1.8",
"css-loader": "^0.26.1",
"extract-text-webpack-plugin": "^2.0.0-rc.3",
"node-sass": "^4.5.0",
"sass-loader": "^6.0.0",
"style-loader": "^0.13.1"
}
Posting here because there isn't really room in the comments...if you have a link to the repo I might be able to be more helpful. Your syntax doesn't look wrong necessarily, but I am posting this because it's the most recent example I have that I know works: you might want to try using option instead of query. It doesn't look like query is deprecated based on the documentation, but this setup worked for me (although I wasn't using extract here),
{
test: /\.scss$/,
use: [
'style-loader?sourceMap',
{
loader: 'css-loader',
options: {
sourceMap: true,
importLoaders: 2,
}
},
'postcss-loader?sourceMap',
'sass-loader?sourceMap'
],
exclude: [path.resolve('node_modules')],
},

Resources