Storybook can't process TS files outside of the project - reactjs

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;
}

Related

Field 'browser' doesn't contain a valid alias configuration for storybook in react

The project is nextjs. align written in jsconfig.json file and it is working when i run the project. the problam is when i run yarn storybook
.storybook/main.js file
module.exports = {
addons: ["#storybook/addon-links", "#storybook/addon-essentials"],
core: {
builder: {
name: "webpack5",
options: {
fsCache: true,
},
},
},
stories: ["../src/**/*.stories.#(js|mdx)"],
};
I use a module resolver, like the following line of code, to fix the problem.
webpackFinal: async (config, { configType }) => {
config.resolve.alias = {
...config.resolve.alias,
"#hooks": path.resolve(__dirname, "../src/hooks"),
.
.
.
}
}

Cannot convert lodash library from CommonJS to ES in Vitejs

I am building a project using Vite + React + Antd.
My project has lodash library, when i build with vite build command then get an error like below:
Running on environment production
vite v2.9.9 building for production...
transforming (2741) node_modules\.pnpm\lodash#4.17.21\node_modules\lodash\isLength.jsUnexpected early exit. This happens when Promises returned by plugins cannot resolve. Unfinished hook action(s) on exit:
(commonjs) load "\u0000cross-fetch?commonjs-proxy"
error during build:
Error: Unexpected early exit. This happens when Promises returned by plugins cannot resolve. Unfinished hook action(s) on exit:
(commonjs) load "\u0000cross-fetch?commonjs-proxy"
In my vite.config.js file, I added #rollup/plugin-commonjs,
import commonjs from '#rollup/plugin-commonjs';
import react from '#vitejs/plugin-react';
import { defineConfig, loadEnv } from 'vite';
export default ({ mode }) => {
const env = loadEnv(mode, 'env');
const htmlPlugin = () => {
return {
name: 'html-transform',
// Replace %VITE_X% env variables in index.html.
transformIndexHtml(html: string) {
return html.replace(/%(.*?)%/g, function match(_match, p1) {
return env[p1];
});
},
};
};
return defineConfig({
resolve: {
alias: [
{ find: /^~/, replacement: '' },
{ find: 'react/jsx-runtime', replacement: 'react/jsx-runtime.js' },
],
},
define: {
'process.env': process.env,
},
build: {
outDir: './build',
rollupOptions: {
plugins: [commonjs()],
},
commonjsOptions: {
exclude: [/./],
},
},
publicDir: './public',
css: {
preprocessorOptions: {
less: {
javascriptEnabled: true,
},
},
},
optimizeDeps: {
include: ['#ant-design/icons'],
},
plugins: [
htmlPlugin(),
react({
babel: {
plugins: [['#babel/plugin-transform-react-jsx', { runtime: 'automatic' }]],
},
}),
],
});
};
I tried to change lodash into lodash-es, but in my node_modules has a couple of libraries use it.
Please help me. Thank all

SyntaxError: pragma and pragmaFrag cannot be set when runtime is automatic

I'm migrating a project from Next 9 to Next 11 which uses webpack5 by default. After fixing the loader issue as shown in the next.config.js file, I get this error:
SyntaxError: pragma and pragmaFrag cannot be set when runtime is automatic
I've tried debugging with these solutions, and I still trigger the same error.
My code:
next.config.js
const withImages = require("next-images");
const { PHASE_DEVELOPMENT_SERVER } = require("next/constants");
const withYaml = require("next-plugin-yaml");
const babel = require('babel-plugin-import-glob-array');
module.exports = (phase) =>
withYaml(
withImages(
({
target: "serverless",
env: {
isDev: phase === PHASE_DEVELOPMENT_SERVER,
},
webpack5: true,
webpack: (config, options) => {
config.module.rules.push({
test: /\.mdx/,
use: [
options.defaultLoaders.babel,
{
loader: '#mdx-js/loader',
options: babel.options,
},
],
});
config.module.rules.unshift({
test: /\.svg$/,
use: ["#svgr/webpack"]
});
console.log(options.webpack.version); // 5.18.0
// eslint-disable-next-line no-param-reassign
config.experiments = {};
return config;
},
})
)
);
babel.config.json
{
"presets": ["next/babel", "#emotion/babel-preset-css-prop"],
"plugins": ["import-glob-array", "emotion"]
}
.tsx files
/** #jsx jsx */
import { css, jsx } from "#emotion/core";

How to make aliases with Storybook?

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
}
}

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',
],
},
},
}
}]
},
}

Resources