Skip to content

Commit

Permalink
fix(react): add missing style preprocessors when using Vite (#13600)
Browse files Browse the repository at this point in the history
  • Loading branch information
jaysoo committed Dec 2, 2022
1 parent 3e2b8d9 commit 67c7822
Show file tree
Hide file tree
Showing 18 changed files with 195 additions and 17 deletions.
6 changes: 6 additions & 0 deletions docs/generated/packages/vite.json
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,12 @@
"type": "boolean",
"default": false,
"description": "Skip generating a vite config file"
},
"coverageProvider": {
"type": "string",
"enum": ["c8", "istanbul"],
"default": "c8",
"description": "Coverage provider to use."
}
},
"required": ["project"],
Expand Down
28 changes: 27 additions & 1 deletion packages/react/src/generators/application/application.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -970,7 +970,8 @@ describe('app', () => {

describe('setup React app with --bundler=vite', () => {
let viteAppTree: Tree;
beforeAll(async () => {

beforeEach(async () => {
viteAppTree = createTreeWithEmptyV1Workspace();
await applicationGenerator(viteAppTree, { ...schema, bundler: 'vite' });
});
Expand All @@ -984,6 +985,7 @@ describe('app', () => {
buildTarget: 'my-app:build',
});
});

it('should add dependencies in package.json', () => {
const packageJson = readJson(viteAppTree, '/package.json');

Expand Down Expand Up @@ -1020,6 +1022,30 @@ describe('app', () => {
viteAppTree.exists('/apps/insourceTests/src/app/app.spec.tsx')
).toBe(false);
});

it.each`
style | pkg
${'less'} | ${'less'}
${'scss'} | ${'sass'}
${'styl'} | ${'stylus'}
`(
'should add style preprocessor when vite is used',
async ({ style, pkg }) => {
await applicationGenerator(viteAppTree, {
...schema,
style,
bundler: 'vite',
unitTestRunner: 'vitest',
name: style,
});

expect(readJson(viteAppTree, 'package.json')).toMatchObject({
devDependencies: {
[pkg]: expect.any(String),
},
});
}
);
});

describe('setting generator defaults', () => {
Expand Down
4 changes: 4 additions & 0 deletions packages/react/src/generators/application/application.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ import {
swcCoreVersion,
swcLoaderVersion,
} from '../../utils/versions';
import { installCommonDependencies } from './lib/install-common-dependencies';

async function addLinting(host: Tree, options: NormalizedSchema) {
const tasks: GeneratorCallback[] = [];
Expand Down Expand Up @@ -122,6 +123,7 @@ export async function applicationGenerator(host: Tree, schema: Schema) {

const vitestTask = await vitestGenerator(host, {
uiFramework: 'react',
coverageProvider: 'c8',
project: options.projectName,
inSourceTests: options.inSourceTests,
});
Expand Down Expand Up @@ -153,6 +155,8 @@ export async function applicationGenerator(host: Tree, schema: Schema) {

// Handle tsconfig.spec.json for jest or vitest
updateSpecConfig(host, options);
const stylePreprocessorTask = installCommonDependencies(host, options);
tasks.push(stylePreprocessorTask);
const styledTask = addStyledModuleDependencies(host, options.styledModule);
tasks.push(styledTask);
const routingTask = addRouting(host, options);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { addDependenciesToPackageJson, Tree } from '@nrwl/devkit';
import {
lessVersion,
sassVersion,
stylusVersion,
} from '../../../utils/versions';
import { NormalizedSchema } from '../schema';

export function installCommonDependencies(
host: Tree,
options: NormalizedSchema
) {
let devDependencies = null;

// Vite requires style preprocessors to be installed manually.
// `@nrwl/webpack` installs them automatically for now.
// TODO(jack): Once we clean up webpack we can remove this check
if (options.bundler === 'vite' || options.unitTestRunner === 'vitest') {
switch (options.style) {
case 'scss':
devDependencies = { sass: sassVersion };
break;
case 'less':
devDependencies = { less: lessVersion };
break;
case 'styl':
devDependencies = { stylus: stylusVersion };
break;
}
}

return devDependencies
? addDependenciesToPackageJson(host, {}, devDependencies)
: function noop() {};
}
1 change: 1 addition & 0 deletions packages/react/src/generators/component/component.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -312,6 +312,7 @@ describe('component', () => {
.read('libs/my-lib/src/lib/hello/hello.tsx')
.toString();
expect(content).toContain('<style jsx>');
expect(content).not.toContain("styles['container']");
});

it('should add dependencies to package.json', async () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import { Route, Link } from 'react-router-dom';
import styled from '<%= styledModule %>';
<% } else {
var wrapper = 'div';
var extras = globalCss ? '' : " className={styles['container']}";
var extras = globalCss || styledModule === 'styled-jsx' ? '' : " className={styles['container']}";
%>
<%- style !== 'styled-jsx' ? globalCss ? `import './${fileName}.${style}';` : `import styles from './${fileName}.module.${style}';`: '' %>
<% }
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import { addDependenciesToPackageJson, Tree } from '@nrwl/devkit';
import {
lessVersion,
reactDomVersion,
reactVersion,
sassVersion,
stylusVersion,
swcCoreVersion,
} from '../../../utils/versions';
import { NormalizedSchema } from '../schema';

export function installCommonDependencies(
host: Tree,
options: NormalizedSchema
) {
const devDependencies =
options.compiler === 'swc' ? { '@swc/core': swcCoreVersion } : {};

// Vite requires style preprocessors to be installed manually.
// `@nrwl/webpack` installs them automatically for now.
// TODO(jack): Once we clean up webpack we can remove this check
if (options.bundler === 'vite' || options.unitTestRunner === 'vitest') {
switch (options.style) {
case 'scss':
devDependencies['sass'] = sassVersion;
break;
case 'less':
devDependencies['less'] = lessVersion;
break;
case 'styl':
devDependencies['stylus'] = stylusVersion;
break;
}
}

return addDependenciesToPackageJson(
host,
{
react: reactVersion,
'react-dom': reactDomVersion,
},
devDependencies
);
}
24 changes: 24 additions & 0 deletions packages/react/src/generators/library/library.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -771,4 +771,28 @@ describe('lib', () => {
}).not.toThrow();
}
);

it.each`
style | pkg
${'less'} | ${'less'}
${'scss'} | ${'sass'}
${'styl'} | ${'stylus'}
`(
'should add style preprocessor when vite is used',
async ({ style, pkg }) => {
await libraryGenerator(tree, {
...defaultSchema,
style,
bundler: 'vite',
unitTestRunner: 'vitest',
name: 'myLib',
});

expect(readJson(tree, 'package.json')).toMatchObject({
devDependencies: {
[pkg]: expect.any(String),
},
});
}
);
});
19 changes: 4 additions & 15 deletions packages/react/src/generators/library/library.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import {
addDependenciesToPackageJson,
addProjectConfiguration,
convertNxGenerator,
ensurePackage,
Expand All @@ -11,12 +10,7 @@ import {
} from '@nrwl/devkit';
import { runTasksInSerial } from '@nrwl/workspace/src/utilities/run-tasks-in-serial';

import {
nxVersion,
reactDomVersion,
reactVersion,
swcCoreVersion,
} from '../../utils/versions';
import { nxVersion } from '../../utils/versions';
import componentGenerator from '../component/component';
import initGenerator from '../init/init';
import { Schema } from './schema';
Expand All @@ -27,6 +21,7 @@ import { addLinting } from './lib/add-linting';
import { updateAppRoutes } from './lib/update-app-routes';
import { createFiles } from './lib/create-files';
import { updateBaseTsConfig } from './lib/update-base-tsconfig';
import { installCommonDependencies } from './lib/install-common-dependencies';

export async function libraryGenerator(host: Tree, schema: Schema) {
const tasks: GeneratorCallback[] = [];
Expand Down Expand Up @@ -123,6 +118,7 @@ export async function libraryGenerator(host: Tree, schema: Schema) {
const vitestTask = await vitestGenerator(host, {
uiFramework: 'react',
project: options.name,
coverageProvider: 'c8',
inSourceTests: options.inSourceTests,
});
tasks.push(vitestTask);
Expand Down Expand Up @@ -153,14 +149,7 @@ export async function libraryGenerator(host: Tree, schema: Schema) {
}

if (!options.skipPackageJson) {
const installReactTask = await addDependenciesToPackageJson(
host,
{
react: reactVersion,
'react-dom': reactDomVersion,
},
options.compiler === 'swc' ? { '@swc/core': swcCoreVersion } : {}
);
const installReactTask = await installCommonDependencies(host, options);
tasks.push(installReactTask);
}

Expand Down
5 changes: 5 additions & 0 deletions packages/react/src/utils/versions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,3 +52,8 @@ export const isbotVersion = '^3.6.5';
export const corsVersion = '~2.8.5';
export const typesCorsVersion = '~2.8.12';
export const moduleFederationNodeVersion = '~0.9.6';

// style preprocessors
export const lessVersion = '3.12.2';
export const sassVersion = '^1.55.0';
export const stylusVersion = '^0.55.0';
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ export async function viteConfigurationGenerator(tree: Tree, schema: Schema) {
project: schema.project,
uiFramework: schema.uiFramework,
inSourceTests: schema.inSourceTests,
coverageProvider: 'c8',
skipViteConfig: true,
});
tasks.push(vitestTask);
Expand Down
1 change: 1 addition & 0 deletions packages/vite/src/generators/vitest/schema.d.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
export interface VitestGeneratorSchema {
project: string;
uiFramework: 'react' | 'none';
coverageProvider: 'c8' | 'istanbul';
inSourceTests?: boolean;
skipViteConfig?: boolean;
}
6 changes: 6 additions & 0 deletions packages/vite/src/generators/vitest/schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,12 @@
"type": "boolean",
"default": false,
"description": "Skip generating a vite config file"
},
"coverageProvider": {
"type": "string",
"enum": ["c8", "istanbul"],
"default": "c8",
"description": "Coverage provider to use."
}
},
"required": ["project"]
Expand Down
21 changes: 21 additions & 0 deletions packages/vite/src/generators/vitest/vitest-generator.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import {
addDependenciesToPackageJson,
convertNxGenerator,
formatFiles,
generateFiles,
Expand All @@ -18,6 +19,10 @@ import { VitestGeneratorSchema } from './schema';

import { runTasksInSerial } from '@nrwl/workspace/src/utilities/run-tasks-in-serial';
import initGenerator from '../init/init';
import {
vitestCoverageC8Version,
vitestCoverageIstanbulVersion,
} from '../../utils/versions';

export async function vitestGenerator(
tree: Tree,
Expand Down Expand Up @@ -45,6 +50,22 @@ export async function vitestGenerator(
createFiles(tree, schema, root);
updateTsConfig(tree, schema, root);

const installCoverageProviderTask = addDependenciesToPackageJson(
tree,
{},
schema.coverageProvider === 'istanbul'
? {
'@vitest/coverage-istanbul': vitestCoverageIstanbulVersion,
}
: {
'@vitest/coverage-c8': vitestCoverageC8Version,
}
);
tasks.push(installCoverageProviderTask);

if (schema.coverageProvider === 'istanbul') {
}

await formatFiles(tree);

return runTasksInSerial(...tasks);
Expand Down
7 changes: 7 additions & 0 deletions packages/vite/src/generators/vitest/vitest.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ describe('vitest generator', () => {
const options: VitestGeneratorSchema = {
project: 'my-test-react-app',
uiFramework: 'react',
coverageProvider: 'c8',
};

beforeEach(async () => {
Expand Down Expand Up @@ -126,6 +127,9 @@ describe('vitest generator', () => {
test: {
globals: true,
cache: {
dir: '../../node_modules/.vitest'
},
environment: 'jsdom',
include: ['src/**/*.{test,spec}.{js,mjs,cjs,ts,mts,cts,jsx,tsx}'],
Expand Down Expand Up @@ -169,6 +173,9 @@ describe('vitest generator', () => {
},
test: {
globals: true,
cache: {
dir: '../../node_modules/.vitest'
},
environment: 'jsdom',
include: ['src/**/*.{test,spec}.{js,mjs,cjs,ts,mts,cts,jsx,tsx}'],
includeSource: ['src/**/*.{js,mjs,cjs,ts,mts,cts,jsx,tsx}']
Expand Down
3 changes: 3 additions & 0 deletions packages/vite/src/utils/generator-utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -354,6 +354,9 @@ export function writeViteConfig(tree: Tree, options: Schema) {
const testOption = options.includeVitest
? `test: {
globals: true,
cache: {
dir: '${offsetFromRoot(projectConfig.root)}node_modules/.vitest'
},
environment: 'jsdom',
include: ['src/**/*.{test,spec}.{js,mjs,cjs,ts,mts,cts,jsx,tsx}'],
${
Expand Down
4 changes: 4 additions & 0 deletions packages/vite/src/utils/versions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,7 @@ export const vitePluginVueJsxVersion = '^2.1.1';
export const viteTsConfigPathsVersion = '^3.5.2';
export const jsdomVersion = '~20.0.3';
export const vitePluginDtsVersion = '~1.7.1';

// Coverage providers
export const vitestCoverageC8Version = '~0.25.3';
export const vitestCoverageIstanbulVersion = '~0.25.3';
1 change: 1 addition & 0 deletions packages/web/src/generators/application/application.ts
Original file line number Diff line number Diff line change
Expand Up @@ -220,6 +220,7 @@ export async function applicationGenerator(host: Tree, schema: Schema) {
const vitestTask = await vitestGenerator(host, {
uiFramework: 'none',
project: options.projectName,
coverageProvider: 'c8',
inSourceTests: options.inSourceTests,
});
tasks.push(vitestTask);
Expand Down

1 comment on commit 67c7822

@vercel
Copy link

@vercel vercel bot commented on 67c7822 Dec 2, 2022

Choose a reason for hiding this comment

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

Successfully deployed to the following URLs:

nx-dev – ./

nx-dev-git-master-nrwl.vercel.app
nx.dev
nx-dev-nrwl.vercel.app
nx-five.vercel.app

Please sign in to comment.