Babel config to SWC - babel-loader

Now I have such babel config on the project and I really want to rewrite this case under swc. Would anyone be able to help with this
module.exports = {
sourceMaps: true,
presets: [
[
'#babel/preset-env',
{
exclude: ['transform-async-to-generator', 'transform-regenerator'],
},
],
'#babel/preset-react',
[
'#babel/preset-typescript',
{
isTSX: true,
allExtensions: true,
},
],
],
plugins: [
'#babel/plugin-syntax-dynamic-import',
['#babel/plugin-proposal-decorators', { legacy: true }],
['#babel/plugin-proposal-class-properties', { loose: true }],
['module:fast-async', { spec: true }],
[
'#babel/plugin-transform-regenerator',
{
asyncGenerators: true,
generators: true,
async: false,
},
],
],
};
Now I have written such a config, but part of the application has stopped working with similar errors: [MobX] Cannot decorate undefined property: 'description'
test: /\.(tsx|ts|jsx|js)$/,
loader: 'swc-loader',
options: {
jsc: {
keepClassNames: true,
parser: {
syntax: 'typescript',
decorators: true,
tsx: true,
dynamicImport: true,
preserveAllComments: false
},
transform: {
legacyDecorator: true,
decoratorMetadata: true
},
loose: false
},
},

Related

How to include node_modules in a bundle file using webpack?

please help me.
I'm to creating utilize webpack to bundle a simple project. but this problem is that the output
file contains module.exports = require(...).
I want to have everything in one bundle file without module.exports.
main.ts
import moment from "moment";
console.log(moment().year());
main.js <- writed bandle file
/***/ ((module) => {
module.exports = require("moment"); // <- I don't want
/***/ })
webpack.config.ts
module.exports = {
entry: {
main: ["/workspace/apps/background/src/main.ts"],
},
devtool: "source-map",
mode: "development",
output: {
path: "/workspace/dist/background",
filename: "main.js",
hashFunction: "xxhash64",
pathinfo: false,
libraryTarget: "umd",
globalObject: "this",
},
module: {
unsafeCache: true,
rules: [
{
test: {},
loader: "/workspace/node_modules/ts-loader/index.js",
exclude: {},
options: {
configFile: "/workspace/apps/background/tsconfig.app.json",
transpileOnly: true,
experimentalWatchApi: true,
},
},
],
},
resolve: {
extensions: [".ts", ".tsx", ".mjs", ".js", ".jsx"],
alias: {},
plugins: [
{
source: "described-resolve",
target: "resolve",
extensions: [".ts", ".tsx", ".mjs", ".js", ".jsx"],
log: {},
baseUrl: "../..",
absoluteBaseUrl: "/workspace",
},
],
mainFields: ["es2015", "module", "main"],
},
performance: {
hints: false,
},
plugins: [
{
options: {
async: false,
typescript: {
enabled: true,
configFile: "/workspace/apps/background/tsconfig.app.json",
memoryLimit: 2048,
},
},
},
{
patterns: [
{
context: "/workspace/apps/background/src/assets",
to: "assets",
from: "**/*",
globOptions: {
ignore: [".gitkeep", "**/.DS_Store", "**/Thumbs.db"],
dot: true,
},
},
],
options: {},
},
],
watch: false,
watchOptions: {
aggregateTimeout: 200,
},
stats: {
hash: true,
timings: false,
cached: false,
cachedAssets: false,
modules: false,
warnings: true,
errors: true,
colors: true,
chunks: true,
assets: false,
chunkOrigins: false,
chunkModules: false,
children: false,
reasons: false,
version: false,
errorDetails: false,
moduleTrace: false,
usedExports: false,
},
experiments: {
cacheUnaffected: true,
},
target: "node",
node: false,
externals: [null],
};
Is there any solution?

How to disable removeViewBox plugin in Next.Js and svgr?

I would like to disable the removeViewBox plugin in Next.js/svgr/svgo. The following next.config.js should work but it does not.
Anybody can help ?
I'm using it with:
"#svgr/webpack": "^6.2.0", "react": "17.0.2", "next": "^12.0.7",
module.exports = {
reactStrictMode: true,
i18n,
webpack(config) {
config.module.rules.push(
{
test: /\.svg$/i,
issuer: /\.[jt]sx?$/,
use: [
{
loader: '#svgr/webpack',
options: {
prettier: false,
svgo: true,
icon: true,
svgoConfig: {
plugins: [
{
name: 'preset-default',
params: {
overrides: {
removeViewBox: false,
},
},
},
],
},
titleProp: true,
},
},
],
})
return config
},
}
For #svgr/webpack#5.5.0 it worked when I added { removeViewBox: false } right to plugins array:
{
loader: '#svgr/webpack',
options: {
svgoConfig: {
plugins: [
{ removeViewBox: false },
],
},
},
},
This is what's worked for my with next#13.0.5 and #svgr/webpack#6.5.1
config.module.rules.push({
test: /\.svg$/i,
issuer: /\.[jt]sx?$/,
use: [{ loader: '#svgr/webpack', options: { icon: true } }]
});

ESLint + Prettier formatOnSave does work but not Alt + Shift + F

I've created a separate repo with shared eslint config for different projects in my org:
module.exports = {
parser: '#typescript-eslint/parser', // Specifies the ESLint parser
extends: [
'airbnb-base',
'plugin:#typescript-eslint/recommended',
'prettier',
'plugin:import/errors',
'plugin:import/warnings',
'plugin:import/typescript',
'plugin:jest/recommended',
'plugin:prettier/recommended',
],
plugins: ['#typescript-eslint', 'jest', 'prettier'],
parserOptions: {
ecmaVersion: 12,
sourceType: 'module',
},
env: {
node: true,
es6: true,
jest: true,
},
rules: {
'eol-last': ['error', 'always'],
'newline-before-return': 'error',
'import/extensions': 0,
'import/no-extraneous-dependencies': [
'error',
{
devDependencies: false,
optionalDependencies: false,
peerDependencies: false,
},
],
'no-restricted-imports': [
'error',
{
patterns: [
{
group: ['.prisma/*'],
message: 'Use #prisma instead of .prisma',
},
],
},
],
'semi': 'error',
'comma-dangle': 'off',
'#typescript-eslint/comma-dangle': ['error', 'always-multiline'],
'indent': 'off',
'quotes': 'off',
'#typescript-eslint/quotes': [
'error',
'single',
{
allowTemplateLiterals: true,
},
],
'#typescript-eslint/no-shadow': ['error'],
'arrow-parens': ['error', 'always'],
'#typescript-eslint/indent': [
'error',
2,
{
/**
* This should stay here until https://github.com/typescript-eslint/typescript-eslint/issues/1824 is fixed
* as currently it forces you to add additional double-space indent to function arguments with decorators
*/
ignoredNodes: ['FunctionExpression'],
SwitchCase: 1,
},
],
'#typescript-eslint/no-non-null-assertion': 'off',
'#typescript-eslint/no-unused-vars': [
'warn',
{
argsIgnorePattern: '^_',
},
],
'spaced-comment': ['error', 'always'],
'no-multiple-empty-lines': [
'error',
{
max: 2,
maxEOF: 0,
},
],
'import/order': [
'error',
{
'groups': [['external', 'internal', 'builtin'], ['sibling', 'parent'], 'index', 'object'],
'pathGroupsExcludedImportTypes': ['builtin'],
'newlines-between': 'always',
'alphabetize': {
order: 'asc',
caseInsensitive: true,
},
},
],
},
settings: {
'import/resolver': {
node: {
extensions: ['.js', '.ts', '.jsx', '.tsx'],
},
},
},
overrides: [
{
files: ['*.ts', '*.tsx'],
rules: {
'no-undef': 'off',
},
},
{
files: ['next.config.js'],
rules: {
'#typescript-eslint/no-var-requires': 'off',
},
},
],
};
Then I published this package to my private registry and installed it on the other repository where I used it to extend from in that repo's eslint config:
module.exports = {
extends: '#flaut-org/eslint-config',
ignorePatterns: ['.eslintrc.js'],
rules: {
'import/order': [
'error',
{
'groups': [['external', 'internal', 'builtin'], ['sibling', 'parent'], 'index', 'object'],
'pathGroups': [
{
pattern: '#nestjs/**',
group: 'external',
position: 'after',
},
],
'pathGroupsExcludedImportTypes': ['builtin'],
'newlines-between': 'always',
'alphabetize': {
order: 'asc',
caseInsensitive: true,
},
},
],
},
};
But for some reason autoformatting didn't work in VSCode. I've configured my default formatter to be Prettier - Code formatter and retried - didn't do the trick. Then I've added the following lines to my ./vscode/settings.json config:
{
"eslint.validate": [
"javascript",
"typescript"
],
"editor.codeActionsOnSave": {
"source.fixAll.eslint": true
},
"[typescript]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
}
And VSCode actually started auto-formatting it on Ctrl + S, but Alt + Shift + F combination still doesn't work. I've checked both Prettier and ESLint logs and there were no errors and warnings whatsoever. What am I missing that does not allow me to use Alt + Shift + F combination ?

Pass options to the builtin svgo from svgr/webpack

Is there an option to pass in svgo options to the svgr/webpack loader ? I want to remove the width & height attributes and keep the viewbox, by default it removes those.
{
test: /\.svg$/,
use: ['#svgr/webpack'],
options : {
svgo: { // Something like this ?
mergePaths: false,
removeViewbox: false,
removeAttrs: true,
}}
},
In my case I got errors that:
plugins should be an array;
Each plugin object requires a name property
So here is what worked for me:
use: {
loader: '#svgr/webpack',
options: {
svgoConfig: {
plugins: [
{
name: 'removeViewBox',
active: false
}
]
}
}
}
https://react-svgr.com/docs/options/
the answer is as the follow...
{
loader: "#svgr/webpack",
options: {
dimensions: false
}
},
It has a little confusing syntax with nested parameters. Here is what I'm using to disable prefixing ids and classnames. I suppose, in your case it will be something like mergePaths.active = false, removeViewbox.active = false.
loader: '#svgr/webpack',
options: {
svgoConfig: {
plugins: [{
prefixIds: {
prefixIds: false,
prefixClassNames: false
}
}]
}
}
I did not test, but I suppose it would look like this (or similar, you might play with it a bit to get the syntax right):
loader: '#svgr/webpack',
options: {
svgoConfig: {
plugins: [{
removePaths: {
active: false,
}
},{
removeViewbox: {
active: false,
}
},{
removeAttrs: {
active: true,
}
}]
}
}
Look into the code here, where you can figure out what props are actually being exported: https://github.com/svg/svgo
I could not find a way of passing arguments through svgr to svgo so I switched to react-svg-loader which has documentation on how to achieve that :
{
test: /\.svg$/,
use: [
'babel-loader',
{
loader: 'react-svg-loader',
options: {
svgo: {
plugins: [{ removeDimensions: true, removeViewBox: false }],
floatPrecision: 2,
},
},
},
],
},
It works as described here or here:
{
test: /\.svg$/,
use: [{
loader: '#svgr/webpack',
options: {
svgoConfig: {
plugins: [
{ mergePaths: false },
{ removeViewbox: false },
{ removeAttrs: true },
],
},
},
}],
}

Sass relative import with webpack

I'm trying to import the SCSS files relative to the component in the same folder but ex:
import './ngg.scss';
The strange thing is when I change the path of this SCSS file or using dev server it's working fine but when I run it for the production it doesn't work as if the SCSS file doesn't exist, I'm using web-pack 4, I can't see the issue really because there are some components use relative import and it's working fine, please help!!
module.exports = function makeWebpackConfig(options) {
var BUILD = options.environment === 'prod';
var DEV_SERVER = process.env.WEBPACK_MODE === 'watch';
var config = {
mode: BUILD ? 'production' : 'development',
optimization: {
chunkIds: 'named',
moduleIds: 'hashed',
namedModules: true,
noEmitOnErrors: true,
usedExports: true,
splitChunks: {
cacheGroups: {
commons: {
test: /[\\/]node_modules[\\/]/,
name: 'vendors',
chunks: 'all'
},
desktop: {
test: /Resources\/desktop\/assets\/js/,
name: 'common-desktop',
chunks: 'initial',
minChunks: 5
},
mobile: {
test: /Resources\/mobile\/assets\/js/,
name: 'common-mobile',
chunks: 'initial',
minChunks: 5
}
}
},
minimizer: [
new UglifyJsPlugin({
cache: true,
parallel: true
})
]
},
entry: options.entry,
resolve: {
alias: options.alias,
extensions: ['.js', '.jsx'],
modules: ['node_modules']
},
output: {
path: options.parameters.path ? options.parameters.path : __dirname + '/../../web/compiled/',
publicPath: publicPath,
filename: BUILD ? '[name].[contenthash].js' : '[name].[hash].js',
chunkFilename: BUILD ? '[name].[contenthash].js' : '[name].[hash].js'
},
devServer: {
disableHostCheck: true,
overlay: {
warnings: true,
errors: true
},
headers: {
'Access-Control-Allow-Origin': '*'
}
}
};
config.module = {
rules: [
{
test: /\.jsx?$/i,
loader: 'babel-loader',
exclude: /node_modules/,
options: {
minified: !DEV_SERVER,
cacheDirectory: DEV_SERVER,
presets: ['es2015', 'react']
}
},
{
test: /\.(gif|png|jpe?g)(\?.*)?$/i,
enforce: 'pre',
loader: 'image-webpack-loader',
options: options.parameters.image_loader_options || !DEV_SERVER ? {
optipng: {
optimizationLevel: 7,
progressive: true
}
} : {
disable: true
}
},
{
test: /\.(png|jpg|jpeg|gif|svg)(\?.*)?$/i,
loader: 'file-loader',
options: {
name: '[name].[hash].[ext]'
}
},
{
test: /\.(eot|ttf|woff|woff2)$/,
loader: 'url-loader',
},
{
test: /\.html$/i,
loader: 'raw-loader'
},
{
test: /\.(css|scss)$/i,
use: [
DEV_SERVER ? 'style-loader' : MiniCssExtractPlugin.loader,
{
loader: 'css-loader',
options: {
minimize: false,
sourceMap: true
}
},
{
loader: 'postcss-loader',
options: {
plugins: function () {
return [
autoprefixer({
browsers: ['last 2 version']
})
];
}
}
},
]
},
{
test: /\.scss$/i,
loader: 'sass-loader?sourceMap',
options: {
enforce: 'pre'
}
}
]
};
config.plugins = [
new MiniCssExtractPlugin({
filename: BUILD ? '[name].[id].[chunkhash].css' : '[name].[hash].css'
}),
new PostCssPipelineWebpackPlugin({
suffix: 'critical',
processor: postcss([
criticalSplit({
output: criticalSplit.output_types.CRITICAL_CSS
})
])
}),
new PostCssPipelineWebpackPlugin({
suffix: 'rest',
processor: postcss([
criticalSplit({
output: criticalSplit.output_types.REST_CSS
})
])
}),
new PostCssPipelineWebpackPlugin({
suffix: 'min',
processor: postcss([
csso({
restructure: false,
comments: false
})
]),
map: {
inline: false
}
}),
new AssetsPlugin({
filename: path.basename(options.manifest_path),
path: path.dirname(options.manifest_path)
}),
new webpack.ProvidePlugin({
React: "react",
ReactDOM: "react-dom",
$: "jquery",
jQuery: "jquery"
})
];
if (BUILD) {
config.devtool = 'nosources-source-map';
} else {
config.devtool = 'source-map';
}
return config;
};
Below is my webpack config
module: {
rules: [{
test: /\.scss$/,
use: [
'style-loader',
MiniCssExtractPlugin.loader,
{
loader: "css-loader",
options: {
minimize: true,
sourceMap: true
}
},
{
loader: "sass-loader"
}
]
}
]
}
Then in my js I only need to import like this
import "css/Client/client.scss";
You can view my full config here

Resources