Lit components do not automatically request an update on property change (problem only in my storybook) - lit-element

This is really odd: I'm using lit in a storybook (using #storybook/html).
I do not know why, but in my environment lit does not update the component automatically when a property has been changed. If I call requestUpdate explicitly, it is indeed updating.
This happens with every component, even this very simple demo component (shows 'waiting...' first, and after 3 seconds it should show 'done') ... working obviously in this codesandbox ... but not working in my storybook :-(
https://codesandbox.io/s/weathered-river-087wz?file=/src/index.ts
Is there by any change anybody who might have an idea what could be the reason for this strange issue? TYVMIA
[EDIT]: This might be the reason:
https://lit.dev/msg/class-field-shadowing
You should use "useDefineForClassFields": false in tsconfig.json.
Actually I indeed had set it to true, but after changing to false I still have the above issue.
PS: I'm using the latest versions of lit (2.1.1) and storybook (6.4.13)
PPS: Removing directory node_modules and file yarn.lock and running yarn install did not solve the problem

I'm unable to edit Natacha response,
I have the same issue and the following fixed my issue
In tsconfig.json add "useDefineForClassFields": false, in compilerOptions
yarn add -D ts-loader#8.3.0
Add the following to .storybook/main.js:
const path = require('path')
module.exports = {
//...
webpackFinal: async (config) => {
//...
config.module.rules.push({
test: /\.(ts|tsx)$/,
include: path.resolve(__dirname, '../src'),
loader: require.resolve('ts-loader'),
})
return config
},
}

In tsconfig.json you have to set option useDefineForClassFields to false to make lit run properly. For more information please see
https://lit.dev/msg/class-field-shadowing .
To fully solve the issue with Storybook/Webpack I also had to do the following:
yarn add -D ts-loader#8.3.0 (version 9.x does not work with Webpack4)
[EDIT: Please check Vince's answer below ... his solution (= main.js + webpackFinal) seems to be the preferred way]
Adding the following to .storybook/webpack.config.json (not really sure why):
config.module.rules.push({
test: /\.(ts|tsx)$/,
include: path.resolve(__dirname, '../src'),
loader: require.resolve('ts-loader')
})

Related

How to bundle node module CSS into a vscode extension

My Visual Studio Code extension uses the node module highlight.js which comes with a folder full of CSS files. These provide colour schemes for syntax colouring. It has become necessary to bundle some of the CSS files.
It's about bundling an asset
The objective is to bundle a CSS file and at run-time access the file content as a string. If that can be achieved without an import statement that would be perfect. Normally, how exactly one accesses the content of the bundled file would be a separate question, but I have a feeling that content retrieval and how one should go about bundling the asset are closely entwined.
I freely admit to having a weak understanding of WebPack.
The story so far
The bundler is specified in package.json as "webpack": "^5.4.0" but I don't know how to ascertain what is actually present. It is conceivable that there is something wrong with my setup: when I try to run webpack --version on a command prompt in the project folder, it responds
CLI for webpack must be installed.
webpack-cli (https://github.com/webpack/webpack-cli)
We will use "npm" to install the CLI via "npm install -D webpack-cli".
Do you want to install 'webpack-cli' (yes/no):
The first time this happened I responded yes. After a flurry of installation and another try the same thing happened. However, vsce package has no trouble using webpack for a production build and pressing F5 to debug successfully puts together a development build in a dist folder with an unminified file I can examine (which is how I know the file mentioned below is being bundled).
Moving on from there I've modified webpack.config.js like so
//#ts-check
'use strict';
const path = require('path');
/**#type {import('webpack').Configuration}*/
const config = {
target: 'node', // vscode extensions run in a Node.js-context -> https://webpack.js.org/configuration/node/
entry: './src/extension.ts', // the entry point of this extension, -> https://webpack.js.org/configuration/entry-context/
output: {
// the bundle is stored in the 'dist' folder (check package.json), -> https://webpack.js.org/configuration/output/
path: path.resolve(__dirname, 'dist'),
filename: 'extension.js',
libraryTarget: 'commonjs2',
devtoolModuleFilenameTemplate: '../[resource-path]'
},
devtool: 'source-map',
externals: {
vscode: 'commonjs vscode' // the vscode-module is created on-the-fly and must be excluded. Add other modules that cannot be webpack'ed, -> https://webpack.js.org/configuration/externals/
},
resolve: {
// support reading TypeScript and JavaScript files, -> https://github.com/TypeStrong/ts-loader
extensions: ['.ts', '.js', '.css']
},
module: {
rules: [
{
test: /\.ts$/,
exclude: /node_modules/,
use: [
{
loader: 'ts-loader'
}
]
},
{
test: /\.css$/,
use: [
'style-loader',
'css-loader'
]
}
]
}
};
module.exports = config;
As you can see there are rules and loaders for CSS.
When I add this import
import "../node_modules/highlight.js/styles/atelier-dune-light.css";
webpack happily builds the bundle and when I inspect it I can find the bundled CSS.
However, when I try to load the extension in the extension debug host, it fails to load, with this message.
Activating extension 'pdconsec.vscode-print' failed: document is not defined.
Enabling break on caught exceptions reveals this rather surprising exception.
Exception has occurred: Error: Cannot find module 'supports-color'
Require stack:
- c:\Users\Peter\AppData\Local\Programs\Microsoft VS Code\resources\app\node_modules.asar\get-uri\node_modules\debug\src\node.js
- c:\Users\Peter\AppData\Local\Programs\Microsoft VS Code\resources\app\node_modules.asar\get-uri\node_modules\debug\src\index.js
- c:\Users\Peter\AppData\Local\Programs\Microsoft VS Code\resources\app\node_modules.asar\get-uri\dist\index.js
- c:\Users\Peter\AppData\Local\Programs\Microsoft VS Code\resources\app\node_modules.asar\vscode-proxy-agent\out\agent.js
- c:\Users\Peter\AppData\Local\Programs\Microsoft VS Code\resources\app\node_modules.asar\vscode-proxy-agent\out\index.js
- c:\Users\Peter\AppData\Local\Programs\Microsoft VS Code\resources\app\out\bootstrap-amd.js
- c:\Users\Peter\AppData\Local\Programs\Microsoft VS Code\resources\app\out\bootstrap-fork.js
OK, so activation failed because the loader barfed. But WTF does importing CSS have to do with support-color?
Remove the import and it runs just fine. I really don't know how to respond to this; it's not clear to me why a demand for a stylesheet should cause that error. At this point I look to others for guidance and advice.
Remove style-loader from webpack.config.js to fix the error.
Pull the CSS as a string like this. Note the abbreviated path.
const cssPath: string = "highlight.js/styles/atelier-dune-light.css";
const theCss: string = require(cssPath).default.toString();
You do not need the import statement, the use of require will cause Webpack to bundle the files, but you still have to remove style-loader to avoid the loader error.

"TypeError: Cannot read property 'indexOf' of undefined" raised when using packages "onoff" or "rpi-gpio" with WebPack

I wrote a Node.JS project for the Raspberry PI, to control the GPIO.
This is my first time using GPIO.
The project uses the "onoff" package to communicate with GPIO. And the compiler is WebPack.
I can compile the project without issue.
But when I run the application on the RaspberryPI, I receive this error:
webpack:///./node_modules/bindings/bindings.js?:178
if (fileName.indexOf(fileSchema) === 0) {
^
TypeError: Cannot read property 'indexOf' of undefined
at Function.getFileName (webpack:///./node_modules/bindings/bindings.js?:178:16)
at bindings (webpack:///./node_modules/bindings/bindings.js?:82:48)
at eval (webpack:///./node_modules/epoll/epoll.js?:7:86)
at eval (webpack:///./node_modules/epoll/epoll.js?:15:3)
at Object../node_modules/epoll/epoll.js (/home/pi/xilium/raspi.node/Raspi.node/dist/raspi.multi-monitor.js:809:1)
at __webpack_require__ (/home/pi/xilium/raspi.node/Raspi.node/dist/raspi.multi-monitor.js:20:30)
at eval (webpack:///./node_modules/rpi-gpio/rpi-gpio.js?:6:20)
at Object../node_modules/rpi-gpio/rpi-gpio.js (/home/pi/xilium/raspi.node/Raspi.node/dist/raspi.multi-monitor.js:1375:1)
at __webpack_require__ (/home/pi/xilium/raspi.node/Raspi.node/dist/raspi.multi-monitor.js:20:30)
at eval (webpack:///./src/raspi.multi-monitor.ts?:29:15)
So, I tried replacing the "onoff" package with "rpi-gpio". Unfortunately, the result is the same.
It seems that there is a configuration issue for "epoll" package (a dependence of "onoff" and "rpi-gpio").
Can anyone help me?
As a disclaimer, I am new to electron, webpack and everything around it, but after a lot of searching, I finally managed to get it working. I am not sure if this is the proper way to do it yet, but I just got it to work.
While searching far and wide, I found this comment on an issue from the serialport package, where they use electron-rebuild to rebuild the serialport module. More info about using native node modules can be found in the Electron documentation here.
Basically, I this to the scripts of my package.json:
"rebuild": "electron-rebuild -f -w onoff"
Then I ran npm run rebuild. Unfortunately, it still didn't work.
What was the missing link, was to tell webpack that the onoff module should be external.
I did it like so, in the webpack config that builds the electron parts of my app (setup is based on this guide I read):
'use strict';
const path = require('path');
const webpack = require('webpack');
module.exports = {
mode: 'development',
entry: './src/electron/main.js',
output: {
filename: 'index.js',
path: path.resolve(__dirname, 'out/electron')
},
module: {
rules: []
},
resolve: {
extensions: ['.js']
},
plugins: [
// This is the important part for onoff to work
new webpack.ExternalsPlugin('commonjs', [
'onoff'
])
],
// tell webpack that we're building for electron
target: 'electron-main',
node: {
// tell webpack that we actually want a working __dirname value
// (ref: https://webpack.js.org/configuration/node/#node-__dirname)
__dirname: false
}
};
As I wrote this, I stumbled upon externals config that might just work the same as well.
Now, finally I can blink my LEDs. I hope this answer can help anyone else in the future that might have the same issue.

Webpack 1 with transform-loader?brfs on Windows 10

I am using the library pdfkit which uses fontkit which has hardcoded require('fs') in it, no matter if you use it on client or server.
Now the project is in React, using Webpack 1 for packaging. The regular overcoming of the problem is using the following webpack config.
module: {
loaders: [
{
test: /\.json$/,
loader: 'url-loader'
},
{
test: /node_modules\/(pdfkit|fontkit|png-js|linebreak|unicode-properties|brotli)\ //,
loader: "transform-loader?brfs"
},
],
},
This works great on MacOS, Linux and in Docker containers but now working on Windows 10 workstations. I could not find anyone having the same problem.
Edited the following does not resolve completely the case
I managed to overcome it by the following fake library hardcoded in the node_modules/fs/index.js file:
class fsClass {
readFileSync (file) {
return new Promise((resolve) => resolve('fake readFileSync: ' + file));
}
}
const fs = new fsClass();
module.exports = fs;
The project compiles it that way and is working but still I do not think this is the right decision. Any help/ideas would be appreciated!
Thanks!
So far, I have reached only one resolving of the problem. As suggested here:
https://github.com/foliojs/pdfkit/wiki/How-to-compile-standalone-PDFKit-for-use-in-the-browser
$ npm install browserify brfs
$ npm install pdfkit
$ node_modules/.bin/browserify --standalone PDFDocument node_modules/pdfkit/js/pdfkit.js > pdfkit.js
Then copy the file in the src folder and include pdfkit from there. The things work perfectly. The result is - precompiled library in the repo and a Webpack warning for that.
Still will be glad if anyone suggests a better decision

Babel not transpiling ES6 module in node_modules despite proper exclude

In a react project I used react-boilerplate but had private modules to include in the frontend that needed transpiling. In order for babel to transpile those I set exclude to the following function in the webpack config that relates to babel:
rules: [
{
test: /\.js$/, // Transform all .js files required somewhere with Babel
// eslint-disable-next-line object-shorthand, func-names
exclude: function (modulePath) {
return /node_modules/.test(modulePath) &&
!/node_modules\/#trade-quorum\/tq-helpers/.test(modulePath);
},
use: {
loader: 'babel-loader',
options: options.babelQuery,
},
},
And it worked perfectly.
Now I used that same trick in a different project but this time, in the resulting bundle tq-helpers is included but not transpiled into ES5 - the ES6 code is directly in the bundle and the build raises an error (more specifically UglifyJS).
There must be a reason around the dependencies to this package that are not the same in the two projects but hard to find. I was wondering whether there is a way to debug in details what babel does for a specific package in order to find the reason.
Thanks you for your help,
Best,
Didier

Webpack: expressing module dependency

I'm trying to require the bootstrap-webpack module in my webpacked application.
It appears to need jQuery, since the bundled javascript then throws the following:
Uncaught ReferenceError: jQuery is not defined
How do I go about specifying to webpack that jQuery is a dependency for the bootstrap-webpack module, to fix this issue? It feels like it should be trivial, but I've been struggling to figure it out.
I've tried adding:
"jquery": "latest"
to the dependecies in the bootstrap-webpack's package.json, but this didn't work. The documentation is incomplete, and I can't seem to find much about this issue. It should be trivial, right? Help!
There are two possible solutions:
Use the ProvidePlugin: It scans the source code for the given identifier and replaces it with a reference to the given module, just like it has been required.
// webpack.config.js
module.exports = {
...
plugins: [
new webpack.ProvidePlugin({
$: "jquery",
jQuery: "jquery"
})
]
};
Use the imports-loader: It provides the possibility to prepend preparations like require() statements.
// webpack.config.js
{
...
module: {
loaders: [
{ test: require.resolve("jquery"), loader: "imports?jQuery=jquery" }
]
}
}
In that case you need to run npm install imports-loader --save before.
Via this github issue.
Install expose-loader and add require('expose?$!expose?jQuery!jquery'); to your main entry point just before you require webpack-bootstrap.
This will set jQuery on the window so any file can get at it. Be careful with this method all files will then have access to that version of jQuery regardless of whether it was explicitly required.

Resources