How to integrate Storybook with Laravel Jetstream + Inertia? - laravel

I made a project scaffolding script from the official laravel one, you can check the next steps to reproduce my issue:
⚠️FOR YOUR SECURITY ALWAYS READ UNKWOWN SCRIPTS BEFORE USING THEM⚠️
Create an example Laravel project with Laravel Sail + Jetstream Inertia with Teams support and Storybook
Scaffold a project with this sript
curl -s https://gist.githubusercontent.com/moracabanas/d264f9b2c6b7d9de6b0b56a091e1cf2d/raw/7fdc986378aa55fd329afd9d02f6d88aa80911ad/jetstream-storybook.sh | bash
Wait until finishes then
cd example-app
Run the laravel stack with Sail
./vendor/bin/sail up -d
Compile resources
./vendor/bin/sail npm run dev
Then you can visit localhost and you are good to go.
How to stop Laravel Sail stack
./vendor/bin/sail down
How to run Storybook
You must edit docker-compose.yml file and map the default Storybook ports - '6006:6006' like this:
version: '3'
services:
laravel.test:
build:
context: ./vendor/laravel/sail/runtimes/8.0
dockerfile: Dockerfile
args:
WWWGROUP: '${WWWGROUP}'
image: sail-8.0/app
ports:
- '${APP_PORT:-80}:80'
++ - '6006:6006'
...
This way Storybook ports are exposed to the machine, otherwise Storybook wont be reachable from localhost:6006
You must ./vendor/bin/sail up -d to let docker picking up those new port definition changes from docker-compose.yml
And then run Storybook with sail npm run storybook
The issue: Tailwind is not working on Storybook
Progress
✔️ Jetstream uses Webpack 5. Use Storybook build for webpack 5
✔️ Jetstream uses PostCSS 8. Use storybook PostCSS addon and configure it like here
❌ Laravel imports tailwind and postcss-import with the following webpack.mix.config:
const mix = require('laravel-mix');
mix.js('resources/js/app.js', 'public/js').vue()
.postCss('resources/css/app.css', 'public/css', [
require('postcss-import'),
require('tailwindcss'),
])
.webpackConfig(require('./webpack.config'));
if (mix.inProduction()) {
mix.version();
}
Where tailwind and postcss-import are loaded. I do not understand why it is not using autoprefixer nor what is postcss-import. I cannot find any documentation for this stack.
So I tried to load them on Storybook with the next postcss.config.js
module.exports = {
plugins: {
tailwindcss: {},
'postcss-import': {},
},
}
But it isn't loading in storybook.
This is why I think Tailwind isn't working in Storybook
info #storybook/vue3 v6.4.0-alpha.22
info
info => Loading presets
info => Loading 1 config file in "/var/www/html/.storybook"
info => Loading 9 other files in "/var/www/html/.storybook"
info => Adding stories defined in "/var/www/html/.storybook/main.js"
info => Using PostCSS preset with postcss#8.3.6
------------ nothing here ------------
info => Using default Webpack5 setup
Now back in default webpack 4 Storybook build you can clearly see postcss.config.js is loaded but webpack 4 build is incompatible:
info #storybook/vue3 v6.4.0-alpha.22
info
info => Cleaning outputDir: /var/www/html/storybook-static
info => Loading presets
info => Compiling manager..
info => Compiling preview..
info => Loading 1 config file in "/var/www/html/.storybook"
info => Using implicit CSS loaders
info => Using custom postcss.config.js
info => Using default Webpack4 setup
ERR! Error: Rule can only have one resource source (provided resource and test + include + exclude)
So the last step I am missing is importing Tailwind and Postcss in Storybook the same way Laravel is doing it.

Related

Laravel + Vue project--[vue-router] Failed to resolve async component default: ChunkLoadError: Loading chunk dashboard failed

I am working on a Laravel and Vue project, at the moment of executing the server
php run serve the project works normally, I can log in normally but, when I run the vue compilation command npm run watch or npm run dev the page stops loading and throws me an error in the console enter image description here
the composition of the webpack.mix.js file is this:
mix.webpackConfig({
output: {
publicPath: '/mediamanager/public',
publicPath: '/',
chunkFilename: 'js/components/[name].js',
}
});

Trouble using NPM package in Laravel application

I've been using Laravel for years, but I've never used NPM packages in my Laravel apps until now. I'm using Laravel Valet as my development environment.
I am trying to utilize a simple package that interfaces with the remove.bg js package but I can't get it working after hours of trying different things.
Here's what I've done:
Installed the package via npm install remove.bg.
The package was complaining that it couldn't find the modules that it depended on (unirest, http, etc), so I installed them via npm install and even added these fallbacks since it was complaining about Webpack 5 and polyfill:
My webpack.mix.js file:
mix.webpackConfig({
resolve: {
fallback: {
fs: require.resolve('browserify-fs'),
crypto: require.resolve('crypto-browserify'),
stream: require.resolve('stream'),
http: require.resolve('stream-http'),
https: require.resolve('https-browserify'),
path: require.resolve('path-browserify'),
zlib: require.resolve('browserify-zlib'),
},
},
});
In my resources/js/bootstrap.js I added:
import { RemoveBgResult, RemoveBgError, removeBackgroundFromImageBase64 } from 'remove.bg';
window.Removebg = require('remove.bg');
Run npm run dev with no errors.
Included <script src="{{ mix('/js/app.js') }}"></script> in my blade template.
However, when I view my page, I get these errors in the console:
app.js:137237 Uncaught TypeError: Cannot read properties of undefined (reading 'prototype')
at Object.inherits (app.js:137237)
at Object../node_modules/browserify-zlib/lib/index.js (app.js:28688)
at __webpack_require__ (app.js:139212)
at Object../node_modules/unirest/index.js (app.js:131192)
at __webpack_require__ (app.js:139212)
at Object../node_modules/remove.bg/dist/index.js (app.js:108502)
at __webpack_require__ (app.js:139212)
at Module../resources/js/bootstrap.js (app.js:16242)
at __webpack_require__ (app.js:139212)
at Object../resources/js/app.js (app.js:16230)
I'm stumped. What am I doing wrong here?
You can missed on webpack.mix.js file
Add this line
mix.js('resources/js/app.js', 'public/js');

How to migrate from laravel mix to pure Webpack?

Given the webpack.mix.js of a fresh Laravel project :
const mix = require('laravel-mix');
/*
|--------------------------------------------------------------------------
| Mix Asset Management
|--------------------------------------------------------------------------
|
| Mix provides a clean, fluent API for defining some Webpack build steps
| for your Laravel application. By default, we are compiling the Sass
| file for the application as well as bundling up all the JS files.
|
*/
mix.js('resources/js/app.js', 'public/js')
.sass('resources/sass/app.scss', 'public/css');
What is the equivalent using just webpack and a webpack.config.js? (Im looking to remove laravel mix as a dependency on an existing project.)
I did find this default file in the source but it did not help me. Is there a way I can see the "compiled/resulting" webpack configuration or a template/starting point that corresponds to laravel mix default settings?
You can, but the result is not very satisfactory.
Create a JS script with this:
console.log (JSON.stringify(
require('./node_modules/laravel-mix/setup/webpack.config.js'), null, 4)
);
and save it in the root folder of your laravel project. Run it with Node and the output will be the configuration object Laravel Mix receives and inputs to webpack.
However, this file is very long and covers a vast amount of settings, which you wouldn't need if you made your file from scratch. Yes, you could try and remove every extra setting you think you can remove without breaking your output, but in the end it's better to learn how Webpack works so you can write better, mode adjusted configs. At least you can use it to understand how it does certain things.
Just put into webpack.mix.js
Mix.listen('configReady', function (config) {
RegExp.prototype.toJSON = RegExp.prototype.toString;
console.log(JSON.stringify(config));
});
So you will get webpack config from your laravel.mix.
With recent laravel-mix you just need to invoke mix.dump() (in the webpack.mix.js script).
The file you referenced seems to point exactly to the default configuration. Why did this not help?
In order to migrate you could
Learn the basics
Extract the dependencies from Laravel mix aǹd add them to your package.json
Hint: The dependencies there are your devDependencies
Start by installing npm install --save-dev everything "webpack", "babel" and prefixed with "-loader".
If you need Sass and extracted css - npm install --save-dev node-sass sass-loader mini-css-extract-plugin.
Minimal example of a webpack config for your mix example from above would be
const path = require('path');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
module.exports = {
entry: './resources/js/app.js',
output: {
filename: 'js/[name].js',
path: path.join(__dirname, 'public')
},
plugins: [
new MiniCssExtractPlugin({
filename: 'css/[name].css'
})
],
module: {
rules: [
{
test: /\.(sa|sc|c)ss$/,
use: [
{
loader: MiniCssExtractPlugin.loader,
},
'css-loader',
'sass-loader'
]
}
]
}
};
Learn the more advanced basics for your use case

VueJS - Module not found: Error: Can't resolve '#babel/runtime/regenerator'

I have this error
Module not found: Error: Can't resolve '#babel/runtime/regenerator' in 'C:\wamp64\www\project-dev\modules\Gallery\Resources\Assets\Backend\Views\Album'
when I execute this command npm run dev.
So to explain my laravel project directory:
app
modules
auth
backend
gallery
themes
admin
node_modules
resources
js
components
router
index.js
store
app.js
sass
views
package.json
webpack.mix.js
So in my router/index.js of vuejs app, I will includes routes from a module.
I make this:
import GalleryRoutes from "../../../../../modules/Gallery/Resources/Assets/Backend/routes";
// Vue Router
const router = new VueRouter({
base: '/admin',
mode: 'history',
routes: [
...constantRoutes,
...GalleryRoutes,
],
linkActiveClass: "active",
linkExactActiveClass: "active",
});
routes.js file from Gallery module:
// Views
import AlbumIndex from './Views/Album/Index.vue'
// Routes
export default [
// AlbumIndex
{
path: 'gallery/albums',
component: AlbumIndex,
name: 'backend.gallery.album.index',
meta: {
heading: 'Gallery',
title: 'Albums',
icon: 'fas fa-images',
showed: true
}
}
];
But I get the error above.
I think this is a bug related to the node_modules folder, I'm not sure.
It's possible to achieve what I want to do? (include .Vue or .js files from outside my root app directory).
PS: I try to make this to try to answer this question: Backend (VueJS) of laravel application with modules approach
Thank you to helping me :)
It's looking for a dependency that is not installed. In your case you can do npm i babel-runtime --save to install that dependency you're missing.
Installing whatwg-fetch fixed the issue for me

Setup Laravel Mix with SASS and PostCSS critical CSS splitting

I want to setup Laravel Mix with mix.sass AND PostCss Critical CSS splitting. In the end I want two files: app.css and app-critical.css.
Unfortunately I can get this to work. One of the setups (webpack.mix.js) I did try:
mix
.js('templates/src/js/app.js', 'web/assets/dist/')
.js('templates/src/js/home.js', 'web/assets/dist/')
.extract(['vue','axios','lazysizes','svgxuse', 'fontfaceobserver'], 'web/assets/dist/vendor.js')
.sass('templates/src/scss/app.scss', 'web/assets/dist/')
.sourceMaps()
.options({
postCss: [
require('postcss-critical-css')({
preserve: false,
minify: false
})
]
})
.browserSync({
proxy: '127.0.0.1:8080',
files: [
'templates/**/*.twig',
'templates/src/js/**/*',
'templates/src/scss/**/*'
]
});
if (mix.inProduction()) {
console.log("In production");
mix.version();
}
When I run the script via 'npm run watch' I get an error:
10% building modules 0/1 modules 1 active ...ign-tools/templates/src/scss/app.scssWithout `from` option PostCSS could generate wrong source map and will not find Browserslist config. Set it to CSS file path or to `undefined` to prevent this warning.
Also, my file is just copying over all the critical styling. The file grows bigger and bigger, expanding the duplicate code everytime the input SCSS/CSS-file changes.
I did try to set up Laravel Mix + mix.sass + one of the following plugins:
https://github.com/zgreen/postcss-critical-css
https://www.npmjs.com/package/postcss-critical-split
Without success :(
Anybody with a working setup or link to an example repository?
Thanks,
Teun

Resources