Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

plasma-web/plasma-b2c: Добавлена сборка без styled-components #942

Merged
merged 3 commits into from
Feb 12, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions packages/plasma-b2c/.gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,8 @@
/index.*
/__helpers
build-sb

# linaria build
src-css
css/*
!css/package.json
5 changes: 5 additions & 0 deletions packages/plasma-b2c/css/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"module": "es/index.js",
"main": "cjs/index.js",
"types": "index.d.ts"
}
9,237 changes: 6,199 additions & 3,038 deletions packages/plasma-b2c/package-lock.json

Large diffs are not rendered by default.

13 changes: 11 additions & 2 deletions packages/plasma-b2c/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,13 @@
"api-report": "npx api-extractor run --local",
"prepare": "npm run build",
"prebuild": "rm -rf ./components ./es ./helpers ./hocs ./hooks ./mixins ./tokens ./types ./utils index.d.ts index.d.ts.map index.js index.js.map",
"build": "npm run build:cjs && npm run build:esm",
"build": "npm run build:cjs && npm run build:esm && npm run build:css",
"postbuild": "npm run generate:typings",
"build:cjs": "BABEL_ENV=cjs SC_NAMESPACE=plasma-b2c babel ./src --out-dir . --extensions .ts,.tsx",
"build:esm": "BABEL_ENV=esm SC_NAMESPACE=plasma-b2c babel ./src --out-dir ./es --extensions .ts,.tsx",
"prebuild:css": "rm -rf src-css && ./scripts/copy-linaria-components.sh",
"build:css": "BABEL_ENV=esm SC_NAMESPACE=plasma-b2c rollup -c",
"postbuild:css": "rm -rf src-css",
"generate:typings": "tsc --outDir . --emitDeclarationOnly",
"storybook": "storybook dev -p ${PORT:-7007} -c .storybook",
"storybook:build": "storybook build -c .storybook -o build-sb",
Expand Down Expand Up @@ -59,7 +62,12 @@
"@babel/preset-env": "7.15.4",
"@babel/preset-react": "7.14.5",
"@babel/preset-typescript": "7.15.0",
"@ironkinoko/rollup-plugin-styles": "4.0.3",
"@linaria/rollup": "5.0.4",
"@microsoft/api-extractor": "7.38.3",
"@rollup/plugin-babel": "6.0.4",
"@rollup/plugin-commonjs": "25.0.7",
"@rollup/plugin-node-resolve": "15.2.3",
"@salutejs/plasma-colors": "0.12.0",
"@salutejs/plasma-cy-utils": "0.80.0-dev.0",
"@salutejs/plasma-icons": "1.181.0-dev.0",
Expand All @@ -84,6 +92,7 @@
"default-browser-id": "2.0.0",
"react": "18.2.0",
"react-dom": "18.2.0",
"rollup": "3.29.4",
"storybook": "7.5.3",
"styled-components": "5.3.1",
"ts-node": "10.3.0",
Expand All @@ -98,4 +107,4 @@
"react"
],
"sideEffects": false
}
}
145 changes: 145 additions & 0 deletions packages/plasma-b2c/rollup.config.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
import path from 'path';
import { createRequire } from 'module'
import { createFilter } from '@rollup/pluginutils'

import { nodeResolve } from '@rollup/plugin-node-resolve';

import linaria from '@linaria/rollup';
import { babel } from '@rollup/plugin-babel';

import styles from "@ironkinoko/rollup-plugin-styles";


const inputDir = 'src-css';
const require = createRequire(import.meta.url)

export default {
input: path.join(inputDir, 'index.ts'),
treeshake: {
propertyReadSideEffects: false,
},
output: [{
preserveModules: true,
dir: 'css/es',
format: 'es',
freeze: false,
esModule: true,
sourcemap: true,
exports: 'named',
assetFileNames: "[name][extname]",
}, {
preserveModules: true,
dir: 'css/cjs',
format: 'cjs',
freeze: false,
esModule: true,
sourcemap: true,
exports: 'named',
assetFileNames: "[name][extname]",
}],
external: (id) => {
if (id.startsWith('regenerator-runtime') || id === 'tslib') {
return false;
}
return !id.startsWith('.') && !path.isAbsolute(id);
},
plugins: [
linaria({
exclude: ['plasma-core/src/collectPackageInfo.ts'],
tagResolver: (source, tag) => {
if (source === '@salutejs/plasma-new-hope') {
if (tag === 'css') {
// TODO: move to node@20
// return import.meta.resolve('@linaria/core/processors/css');
return require.resolve('@linaria/core/processors/css');
}

if (tag === 'styled') {
return require.resolve('@linaria/react/processors/styled');
}
}

return null;
},
}),
nodeResolve({
extensions: ['.tsx', '.ts'],
}),
importCssPlugin(),
// TODO: #717 remove this plugin: it generates index.css but we don't need it
styles({
mode: "extract",
modules: true,
}),
babel({ babelHelpers: 'bundled', extensions: ['.ts', '.tsx'], }),
],
};

function importCssPlugin() {
const filter = createFilter(['**/*.css']);
const styles = {};

return {
name: 'importCssPlugin',
transform(code, id) {
if (!filter(id)) {
return;
}

if (styles[id] !== code && (styles[id] || code)) {
styles[path.relative(inputDir, id)] = code
}

return { code };
},
generateBundle(options, bundle) {
const files = Object.keys(bundle);
files.forEach((file) => {
const root = bundle[file].facadeModuleId
const modules = this.getModuleInfo(root);

// ADD IMPORT FOR CSS MODULES
if (file.endsWith('.css.js')) {
const { code } = bundle[file];
// TODO: #718 cjs modules => require('./file.css');
const importString = `import './${file.replace('.css.js', '.css.css')}';\n`;
this.emitFile({
type: 'asset',
fileName: file,
source: importString + code,
});
} else if (file.endsWith('.js')) {
// ADD IMPORT FOR LINARIA
// linaria
const cssFiles = modules.importedIds
.filter(a => a.includes(inputDir))
.filter(a => !a.endsWith('.module.css') && a.endsWith('.css'))
.map(a => path.relative(inputDir, a))

if (!cssFiles.length) {
return;
}
const imports = [];
cssFiles.forEach(cssFile => {
imports.push(`import './${path.relative(path.dirname(file), cssFile)}';`);
this.emitFile({
type: 'asset',
fileName: cssFile,
source: styles[cssFile],
});
})
if (imports.length) {
const { code } = bundle[file];
this.emitFile({
type: 'asset',
fileName: file,
source: imports.join('\n') + '\n' + code,
});

console.log(`Added css: ${cssFiles} for ${file}`);
}
}
});
},
};
}
35 changes: 35 additions & 0 deletions packages/plasma-b2c/scripts/copy-linaria-components.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
#!/usr/bin/env bash

# Example: Calendar
components=$(grep -R plasma-new-hope src/components | cut -d / -f 3 | sort -u)

mkdir -p src-css/components/
touch src-css/index.ts
touch src-css/index.d.ts
for component in $components; do
if [[ "$component" != "Switch" ]]; then
shuga2704 marked this conversation as resolved.
Show resolved Hide resolved
cp -R src/components/$component src-css/components/;
grep $component src/index.ts >> src-css/index.ts
echo "export * from '../components/$component';" >> css/index.d.ts;

fi
done;

# remove unused tests
rm -rf src-css/components/**/*.component-test.tsx
rm -rf src-css/components/**/*.perftest.tsx
rm -rf src-css/components/**/*.stories.tsx

# plasma-new-hope/styled-components
files=$(find src-css/components -name '*.ts' -or -name '*.tsx');

for file in $files; do
echo $file;
done;

# plasma-new-hope/styled-components => plasma-new-hope
perl -p -i -e "s/\/styled-components//g" $files

#TODO: #1024 удалить обертку styled в спиннере
perl -p -i -e "s/import styled from 'styled-components';//g" src-css/components/Spinner/Spinner.tsx
perl -p -i -e "s/styled\(SpinnerComponent\)\`\`/SpinnerComponent/g" src-css/components/Spinner/Spinner.tsx
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ааа ты тут просто удаляешь обертку и в линарии идет FunctionComponent

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

В линарии идет сразу компонент, без styled, ибо он запрещен в рантайме и это в принципе бессмысленно.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

а в итоге так нельзя будет сделать через компонент, который собрался линарией?

const StyledWrapper = styled.div`
   ${Spinner} {
      background: blue
   }
` 

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Думаю, что да, но зачем нам это?

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ну это нужно было проверить, чтобы убедиться, что у пользователей, которые вот таким образом спиннер стилизуют, поменяв путь с plasma-b2c на plasma-b2c/css, не сломается сборка

Copy link
Collaborator

@neretin-trike neretin-trike Feb 6, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

А зачем ребятам на sc импортировать /css сборку? Мы же сделали этот фикс, чтобы спиннер был обернут в styled из sc, чтобы на сборке на стайледах все было по-прежнему.

ну когда мы обсуждали это, то как раз пришли к такому мнению, что те, кто будут постепенно переезжать с styled-compoennts на линарию, будут иметь и те, и другие импорты (и зависимости)

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

А сборку /css будут юзать те, у кого нет sc (хотя таковых на данный момент нет). И там я не вижу смысла оборачивать именно Спиннер в styled из линарии, ибо зачем?

не, я и не говорю, что оборачивать нужно. Но нужно убедиться, что у пользователей не будет проблем с обратной совместимостью уже существующих компонент

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

А, ну эти проблемы точно будут, и потребуют ручного устранения, ибо конструкция
${Spinner} { background: blue }
ожидает только styled-подобный компонент из SC, и ни стайлед от линарии, ни обычный react.element как минимум не пройдут проверку типов, а если и пройдут, то работать это не будет.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

а такая конструкция валидна только для styled.tagname компонент получается? 🤔

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Это вполне валидный паттерн, как для SC так и для линарии. https://github.com/callstack/linaria/blob/master/docs/BASICS.md#referring-to-another-component-or-class-name

5 changes: 3 additions & 2 deletions packages/plasma-b2c/src/components/Spinner/Spinner.tsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
import styled from 'styled-components';
import { spinnerConfig, component, mergeConfig } from '@salutejs/plasma-new-hope/styled-components';
import styled from 'styled-components';
import { FunctionComponent } from 'react';
shuga2704 marked this conversation as resolved.
Show resolved Hide resolved

import { config } from './Spinner.config';

import type { SpinnerProps } from '.';

const mergedConfig = mergeConfig(spinnerConfig, config);
const SpinnerComponent = component(mergedConfig) as React.FunctionComponent<SpinnerProps>;
const SpinnerComponent = component(mergedConfig) as FunctionComponent<SpinnerProps>;

/**
* Компонент для отображения индикатора загрузки.
Expand Down
5 changes: 5 additions & 0 deletions packages/plasma-web/.gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,8 @@
/index.*
/helpers
build-sb

# linaria build
src-css
css/*
!css/package.json
5 changes: 5 additions & 0 deletions packages/plasma-web/css/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"module": "es/index.js",
"main": "cjs/index.js",
"types": "index.d.ts"
}
Loading
Loading