How to make aliases with Storybook? - reactjs

I try to make aliases for the storybook, but I have looked on the site to find a solution. However, my problem persists, and it doesn't work. I already have some aliases in my original webpack.config.js, but I don't understand how it cannot be cached. So, when I do yarn storybook, I have an error.
Below is my JS file from the .storybook folder; I used the documentation.
main.js
const path = require('path');
const custom = require('../webpack.config.js');
module.exports = {
webpackFinal: async (config) => {
return {
...config,
module: {
...config.module,
rules: [
{
test: /\.scss$/,
use: ['style-loader', 'css-loader', 'sass-loader'],
include: path.resolve(__dirname, '../'),
}
],
},
resolve: { ...config.resolve, alias: custom.resolve.alias}
};
},
"stories": [
"../src/**/*.stories.mdx",
"../src/**/*.stories.#(js|jsx|ts|tsx)",
"../src/**/**/*.stories.#(js|jsx|ts|tsx)",
],
"addons": [
"#storybook/addon-links",
"#storybook/addon-essentials"
],
"core": {
"builder": "webpack5"
}
}
Error
ModuleParseError: Module parse failed: Unexpected token (10:27) You
may need an appropriate loader to handle this file type, currently no
loaders are configured to process this file. See
https://webpack.js.org/concepts#loaders | }; |
const Template = (args) => <Header {...args} />; | | export const Primary = Template.bind({});
at handleParseError (/path/project/node_modules/#storybook/builder-webpack5/node_modules/webpack/lib/NormalModule.js:933:19)
at /path/project/node_modules/#storybook/builder-webpack5/node_modules/webpack/lib/NormalModule.js:1035:5
at processResult (/path/project/node_modules/#storybook/builder-webpack5/node_modules/webpack/lib/NormalModule.js:755:11)
at /path/project/node_modules/#storybook/builder-webpack5/node_modules/webpack/lib/NormalModule.js:819:5
at /path/project/node_modules/loader-runner/lib/LoaderRunner.js:406:3
at iterateNormalLoaders (/mnt/d/Sites/chillwatch/node_modules/loader-runner/lib/LoaderRunner.js:232:10)
at Array. (/path/project/node_modules/loader-runner/lib/LoaderRunner.js:223:4)
at runCallbacks (/path/project/node_modules/enhanced-resolve/lib/CachedInputFileSystem.js:27:15)
at /path/project/node_modules/enhanced-resolve/lib/CachedInputFileSystem.js:200:4
at /path/project/node_modules/graceful-fs/graceful-fs.js:123:16
at FSReqCallback.readFileAfterClose [as oncomplete] (node:internal/fs/read_file_context:75:3)
What am I doing wrong?

GitHub Issue
As mentioned on the above link you can make aliases with the storybook as following:
const path = require("path")
module.exports = {
"webpackFinal": async (config) => {
config.resolve.alias['#'] = path.resolve(__dirname, '../src')
config.resolve.alias['#components'] = path.resolve(__dirname, '../src/components')
return config
}
}

Related

Storybook can't process TS files outside of the project

I have noticed that Storybook can't process Typescript files if they are from another project (monorepo), but it is doing okay with TS files that are within its project.
How do I configure Storybook to handle TS files outside the project?
Structure of the monorepo:
package1
.storybook
main.ts
preview.ts
component.tsx (this component imports file.ts)
component.stories.tsx
package2
file.ts <- (Storybook can't process this file: ModuleParseError: Module parse failed: Unexpected token)
Here is the main.ts config file:
const TsconfigPathsPlugin = require('tsconfig-paths-webpack-plugin');
const path = require('path');
const toPath = (filePath) => path.join(process.cwd(), filePath);
module.exports = {
"stories": [
"../src/**/*.stories.#(mdx|js|jsx|ts|tsx)"
],
"addons": [
"#storybook/addon-links",
"#storybook/addon-essentials",
"#storybook/addon-interactions",
"#storybook/addon-knobs/register",
"#storybook/preset-create-react-app",
"#storybook/addon-a11y",
'storybook-addon-styled-component-theme/dist/preset',
'storybook-addon-themes',
"storybook-dark-mode",
],
"framework": "#storybook/react",
"core": {
"builder": "#storybook/builder-webpack5",
"disableTelemetry": true,
},
features: {
emotionAlias: false,
},
typescript: { reactDocgen: false },
webpackFinal: async (config, { configType }) => {
return {
...config,
resolve: {
...config.resolve,
alias: {
...config.resolve.alias,
'#emotion/core': toPath('node_modules/#emotion/react'),
'emotion-theming': toPath('node_modules/#emotion/react'),
},
plugins: [new TsconfigPathsPlugin()]
},
}
}
}
Here is the error:
ModuleParseError: Module parse failed: Unexpected token (7:11)
File was processed with these loaders:
* ../../node_modules/#pmmmwh/react-refresh-webpack-plugin/loader/index.js
You may need an additional loader to handle the result of these loaders.
| import { Palette as palette } from '../Palette';
|
> const Paper: any = [
| {
If I import the same TS file, but manually precompiled into regular JS - Storybook works.
I have no idea what to try to solve this :(
Add this to .storybook/main.js
webpackFinal: async (config, { configType }) => {
// `configType` has a value of 'DEVELOPMENT' or 'PRODUCTION'
// You can change the configuration based on that.
// 'PRODUCTION' is used when building the static version of storybook.
// Storybook uses its own webpack config, so we need to merge our config with it
// See https://storybook.js.org/docs/configurations/custom-webpack-config/
// Add typescript loader to process TS-files from other packages
config.module.rules.push({
test: /\.(ts|tsx)$/,
use: [
{
loader: require.resolve("ts-loader"),
options: {
reportFiles: [
"../**/src/**/*.{ts,tsx}"
]
}
},
]
});
config.resolve.extensions.push(".ts", ".tsx");
return config;
}

webpack config for nx14 react project

in documentation nx suggest to use merge option to rewrite the default webpack config
https://nx.dev/guides/customize-webpack
so, i put my custom webpack.config.js file in a project.json file
webpack.config.js file:
const { merge } = require('webpack-merge');
module.exports = (config, context) => {
return merge(config, {
module: {
rules: [
{
test: /\.sass$/i,
use: [
'style-loader',
'css-loader',
'sass-loader'
],
},
],
}
});
};
all i am trying to do is just make to read my .sass files as .module.sass
but as result i have many errors

What is the appropriate webpack loader to use static keywords?

I have the following error when I try to start my react-styleguidist documentation:
./node_modules/react-native-gesture-handler/touchables/TouchableHighlight.js 10:22
Module parse failed: Unexpected token (10:22)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
| */
| export default class TouchableHighlight extends Component {
> static defaultProps = {
| ...GenericTouchable.defaultProps,
| activeOpacity: 0.85,
# ./node_modules/react-native-gesture-handler/touchables/index.js 6:0-69 6:0-69
# ./node_modules/react-native-gesture-handler/index.js
My webpack.config.js look like this:
const createExpoWebpackConfigAsync = require('#expo/webpack-config');
module.exports = async function (env, argv) {
const config = await createExpoWebpackConfigAsync(env, argv);
return config;
};
My babel.config.js look like this:
module.exports = function (api) {
api.cache(true);
return {
presets: ['babel-preset-expo'],
env: {
development: {
plugins: [
'#babel/plugin-transform-react-jsx-source',
],
},
},
};
};
Reproduction:
git clone https://github.com/kopax/expo-bug-reports.git
cd expo-bug-reports
git checkout react-styleguidist
npm i
npm run styleguide
What is the appropriate Webpack loader to use the static keyword?
If you use webpack for build your project, then you need to add the babel-loader to webpack.
module: {
rules: [{
test: /\.(j|t)sx?$/,
exclude: [/node_modules/],
use: [{
loader: "babel-loader",
options: {
presets: ['babel-preset-expo'],
env: {
development: {
plugins: [
'#babel/plugin-transform-react-jsx-source',
],
},
},
}
}]
},
}

React - kendo-ui styles module failed to parse - You may need an appropriate loader to handle this file type

I need to import default Kendo-ui template styles from this site https://www.telerik.com/kendo-react-ui/components/styling/.
When it trying to load styles, it throws NodeInvocationException: Prerendering failed because of error: Error: Module parse failed: "project folder"\node_modules\#progress\kendo-theme-default\dist\all.css Unexpected token (1:0)
You may need an appropriate loader to handle this file type.
Here is my layout.ts file where I want to import style template
import * as React from 'react';
import { NavMenu } from './NavMenu';
import "#progress/kendo-theme-default/dist/all.css";
export class Layout extends React.Component<{}, {}> {
public render() {
return <div className='container-fluid'>
<div className='row'>
<div className='col-sm-3'>
<NavMenu />
</div>
<div className='col-sm-9'>
{ this.props.children }
</div>
</div>
</div>;
}
}
webpack.config looks like this, its default configuration from auto generated react-redux asp.net project
const path = require('path');
const webpack = require('webpack');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const CheckerPlugin = require('awesome-typescript-loader').CheckerPlugin;
const merge = require('webpack-merge');
module.exports = (env) => {
const isDevBuild = !(env && env.prod);
// Configuration in common to both client-side and server-side bundles
const sharedConfig = () => ({
stats: { modules: false },
resolve: { extensions: ['.js', '.jsx', '.ts', '.tsx'] },
output: {
filename: '[name].js',
publicPath: 'dist/' // Webpack dev middleware, if enabled, handles requests for this URL prefix
},
module: {
rules: [
{ test: /\.tsx?$/, include: /ClientApp/, use: 'awesome-typescript-loader?silent=true' },
{ test: /\.(png|jpg|jpeg|gif|svg)$/, use: 'url-loader?limit=25000' }
]
},
plugins: [new CheckerPlugin()]
});
// Configuration for client-side bundle suitable for running in browsers
const clientBundleOutputDir = './wwwroot/dist';
const clientBundleConfig = merge(sharedConfig(), {
entry: { 'main-client': './ClientApp/boot-client.tsx' },
module: {
rules: [
{ test: /\.css$/, use: ExtractTextPlugin.extract({ use: isDevBuild ? 'css-loader' : 'css-loader?minimize' }) }
]
},
output: { path: path.join(__dirname, clientBundleOutputDir) },
plugins: [
new ExtractTextPlugin('site.css'),
new webpack.DllReferencePlugin({
context: __dirname,
manifest: require('./wwwroot/dist/vendor-manifest.json')
})
].concat(isDevBuild ? [
// Plugins that apply in development builds only
new webpack.SourceMapDevToolPlugin({
filename: '[file].map', // Remove this line if you prefer inline source maps
moduleFilenameTemplate: path.relative(clientBundleOutputDir, '[resourcePath]') // Point sourcemap entries to the original file locations on disk
})
] : [
// Plugins that apply in production builds only
new webpack.optimize.UglifyJsPlugin()
])
});
// Configuration for server-side (prerendering) bundle suitable for running in Node
const serverBundleConfig = merge(sharedConfig(), {
resolve: { mainFields: ['main'] },
entry: { 'main-server': './ClientApp/boot-server.tsx' },
plugins: [
new webpack.DllReferencePlugin({
context: __dirname,
manifest: require('./ClientApp/dist/vendor-manifest.json'),
sourceType: 'commonjs2',
name: './vendor'
})
],
output: {
libraryTarget: 'commonjs',
path: path.join(__dirname, './ClientApp/dist')
},
target: 'node',
devtool: 'inline-source-map'
});
return [clientBundleConfig, serverBundleConfig];
};
In order for the external .css files to work ( like kendo-theme-default coming from node_modules ), a postcss-loader is required.

mobx-deep-action with Typescript async/await functions and #action decorator

I am struggeling to setup my project correctly to get rid of the mobx error when running in useStrict(true)
Error
mobx.module.js:2238 Uncaught (in promise) Error: [mobx] Invariant failed: Since strict-mode is enabled, changing observed observable values outside actions is not allowed. Please wrap the code in an `action` if this change is intended. Tried to modify: WikiStore#1.tags
at invariant (mobx.module.js:2238)
at fail (mobx.module.js:2233)
at checkIfStateModificationsAreAllowed (mobx.module.js:2794)
at ObservableValue.prepareNewValue (mobx.module.js:750)
at setPropertyValue (mobx.module.js:1605)
at WikiStore.set [as tags] (mobx.module.js:1575)
at WikiStore.<anonymous> (WikiStore.tsx:25)
at step (tslib.es6.js:91)
at Object.next (tslib.es6.js:72)
at fulfilled (tslib.es6.js:62)
My setup compiles but the error is still there, so there must be a mistake in my build chain.
I have used the information provided from the GitHub repo here, but its all a bit vague.
.babelrc
{
"passPerPreset": true,
"presets": [
{
"plugins": ["transform-regenerator"]
},
{
"plugins": ["mobx-deep-action"]
},
{
"plugins": ["babel-plugin-transform-decorators-legacy"]
},
"es2015", "react", "stage-0"
]
}
webpack.config.js
const path = require("path");
const ExtractTextPlugin = require("extract-text-webpack-plugin");
const webpack = require("webpack");
const CheckerPlugin = require('awesome-typescript-loader').CheckerPlugin;
const clientBundleOutputDir = "./wwwroot/dist";
module.exports = (env) => {
const clientConfig = {
stats: { modules: false },
entry: { "main-client": "./Client/index.tsx" },
resolve: { extensions: [".js", ".jsx", ".ts", ".tsx" ] },
output: {
filename: "[name].js",
path: path.join(__dirname, clientBundleOutputDir),
publicPath: "/dist/"
},
module: {
rules: [
{ test: /\.s?css$/, use: ["css-hot-loader"].concat(ExtractTextPlugin.extract({fallback: "style-loader", use: ["css-loader", "sass-loader"]})) },
{ test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/, loader: "url-loader?limit=10000&mimetype=application/font-woff" },
{ test: /\.(ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/, loader: "file-loader" },
{ test: /\.(png|svg|jpg|gif|ico)$/, use: ["file-loader"] },
// { test: /\.tsx?$/, include: /Client/, use: "awesome-typescript-loader?silent=true&useBabel=true&useCache=true" }
{ test: /\.tsx?$/, include: /Client/, use: ["babel-loader", "ts-loader"] }
]
},
plugins: [
new CheckerPlugin(),
new ExtractTextPlugin("site.css"),
new webpack.SourceMapDevToolPlugin({
filename: "[file].map",
moduleFilenameTemplate: path.relative(clientBundleOutputDir, '[resourcePath]')
})
]
};
return [clientConfig];
};
I have tried the awesome typescript loader and also the ts-loader, babel-loader combo.
And here my store (short version)
import { autorun, observable, action } from "mobx";
import { Wiki } from "../models/Wiki";
import { Tag } from "../models/Tag";
import * as Api from "../api/api";
export class WikiStore {
#observable public tags: Tag[] = [];
constructor() {
this.getTags();
}
#action
public async getTags() {
this.tags = await Api.getTags();
}
}
export const wikiStore = new WikiStore();
As soon as i call wikiStore.getTags() from a React component i get the error. Everything just works fine without useStrict(true) (as expected)
Maybe someone has an idea.
I think you still need to split up the await and the assignment:
#action
public async getTags() {
const tags = await Api.getTags();
this.tags.replace(tags);
}
Please read here:
https://mobx.js.org/best/actions.html#async-await
As a result, #action only applies to the code block until the first await
So const tags = await Api.getTags(); must be wrapped again
#action
public async getTags() {
const tags = await Api.getTags();
runInAction(() => {
this.tags = tags;
})
}

Resources