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

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

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

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

Nextjs Error: Must use import to load ES Module

Hi i am creating a project using nextjs and reactjs ,i am facing an issue, when I am trying to import datetime from npm date-time package ,its throwing this error.I am using this npm package https://www.npmjs.com/package/date-time. The error in my code is shown in the picture attached
This is my next.config.js what i need to
const path = require("path");
const withCss = require("#zeit/next-css");
const withSass = require("#zeit/next-sass");
const withImages = require("next-images");
module.exports = withImages(
withSass(
withCss({
webpack: (config, { isServer }) => {
if (isServer) {
config.module.rules.push({
test: /\.(png|jpg|gif|svg|eot|ttf|woff|woff2)$/,
use: {
loader: "url-loader",
options: {
limit: 100000,
name: "[name].[ext]",
},
},
});
}
return config;
},
cssLoaderOptions: {
url: false,
},
})
)
);

How to include multiple plugins with next-css in next.config.js file

I am importing the react-slick css files. When i remove cssModules:true from next.config.js file, everything works fine. Any idea why adding cssModules:true creates the problem?
const withCSS = require("#zeit/next-css");
module.exports = withCSS({
cssModules: true,
webpack: config => {
config.module.rules.push({
test: /\.(eot|woff|woff2|ttf|svg|png|jpg|gif)$/,
use: {
loader: "url-loader",
options: {
limit: 100000,
name: "[name].[ext]"
}
}
});
return config;
}
});

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