Skip to content

Commit

Permalink
misc: convert all internal scripts to ESM (#6286)
Browse files Browse the repository at this point in the history
* misc: convert all internal scripts to ESM

* fixes

* fix

* fixes

* fix!

* complete eslint

* more move

* fix!

* This looks better?

* Final ones
  • Loading branch information
Josh-Cena authored Jan 8, 2022
1 parent bcc05e2 commit 4fad1ce
Show file tree
Hide file tree
Showing 66 changed files with 412 additions and 374 deletions.
4 changes: 1 addition & 3 deletions .eslintignore
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,7 @@ packages/lqip-loader/lib/
packages/docusaurus/lib/
packages/docusaurus-*/lib/*
packages/docusaurus-*/lib-next/
packages/docusaurus-plugin-pwa/copyUntypedFiles.js
packages/docusaurus-plugin-ideal-image/copyUntypedFiles.js
packages/docusaurus-theme-search-algolia/copyUntypedFiles.js
copyUntypedFiles.mjs

packages/create-docusaurus/lib/*
packages/create-docusaurus/templates/facebook/.eslintrc.js
3 changes: 2 additions & 1 deletion .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ module.exports = {
},
},
},
reportUnusedDisableDirectives: true,
plugins: ['react-hooks', 'header'],
rules: {
'react-hooks/rules-of-hooks': ERROR,
Expand Down Expand Up @@ -208,7 +209,7 @@ module.exports = {
},
},
{
files: ['*.js'],
files: ['*.js', '*.mjs', '.cjs'],
rules: {
// Make JS code directly runnable in Node.
'@typescript-eslint/no-var-requires': OFF,
Expand Down
133 changes: 64 additions & 69 deletions generateExamples.js → admin/scripts/generateExamples.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,10 @@
* LICENSE file in the root directory of this source tree.
*/

// eslint-disable-next-line import/no-extraneous-dependencies
const rimraf = require('rimraf');
const {readFileSync, writeFileSync, readdirSync} = require('fs');
const {execSync} = require('child_process');
/* eslint-disable import/no-extraneous-dependencies */

import fs from 'fs-extra';
import shell from 'shelljs';

const NODE_MAJOR_VERSION = parseInt(process.versions.node.split('.')[0], 10);
if (NODE_MAJOR_VERSION < 16) {
Expand All @@ -20,7 +20,7 @@ if (NODE_MAJOR_VERSION < 16) {
// Generate one example per init template
// We use those generated examples as CodeSandbox projects
// See https://github.com/facebook/docusaurus/issues/1699
function generateTemplateExample(template) {
async function generateTemplateExample(template) {
try {
console.log(
`generating ${template} template for codesandbox in the examples folder...`,
Expand All @@ -30,20 +30,17 @@ function generateTemplateExample(template) {
const command = template.endsWith('-typescript')
? template.replace('-typescript', ' -- --typescript')
: template;
execSync(
shell.exec(
// /!\ we use the published init script on purpose,
// because using the local init script is too early and could generate upcoming/unavailable config options
// remember CodeSandbox templates will use the published version, not the repo version
`npm init docusaurus@latest examples/${template} ${command}`,
// `node ./packages/docusaurus-init/bin/index.js init examples/${template} ${template}`,
{
stdio: 'inherit',
},
);

// read the content of the package.json
const templatePackageJson = JSON.parse(
readFileSync(`examples/${template}/package.json`, 'utf8'),
await fs.readFile(`examples/${template}/package.json`, 'utf8'),
);

// attach the dev script which would be used in code sandbox by default
Expand All @@ -64,7 +61,7 @@ function generateTemplateExample(template) {
: `Docusaurus example project (${template} template)`;

// rewrite the package.json file with the new edit
writeFileSync(
await fs.writeFile(
`./examples/${template}/package.json`,
`${JSON.stringify(templatePackageJson, null, 2)}\n`,
);
Expand All @@ -80,7 +77,7 @@ function generateTemplateExample(template) {
node: '14',
},
};
writeFileSync(
await fs.writeFile(
`./examples/${template}/sandbox.config.json`,
`${JSON.stringify(codeSanboxConfig, null, 2)}\n`,
);
Expand All @@ -89,7 +86,7 @@ function generateTemplateExample(template) {
installDependencies: true,
startCommand: 'npm start',
};
writeFileSync(
await fs.writeFile(
`./examples/${template}/.stackblitzrc`,
`${JSON.stringify(stackBlitzConfig, null, 2)}\n`,
);
Expand All @@ -115,7 +112,7 @@ function updateStarters() {
const command = `git push ${remote} \`git subtree split --prefix ${subfolder}\`:${remoteBranch} --force`;
try {
console.log(`forcePushGitSubtree command: ${command}`);
execSync(command);
shell.exec(command);
console.log('forcePushGitSubtree success!');
} catch (e) {
console.error(
Expand Down Expand Up @@ -150,60 +147,58 @@ function updateStarters() {
console.log('');
}

function run() {
const branch = execSync('git rev-parse --abbrev-ref HEAD').toString();
if (branch === 'main') {
throw new Error(
"Please don't generate Docusaurus examples from the main branch!\nWe are going to commit during this process!",
);
}
try {
execSync('git diff --exit-code');
} catch (e) {
throw new Error(
'Please run the generate examples command with a clean Git state and no uncommited local changes. git diff should display nothing!',
);
}

console.log('');
console.log('# Generate examples start!');
console.log('');

// delete the examples directories if they exists
console.log('-------');
console.log('## Removing example folders...');
rimraf.sync('./examples/classic');
rimraf.sync('./examples/classic-typescript');
rimraf.sync('./examples/facebook');
console.log('');

// get the list of all available templates
console.log('-------');
console.log('## Generate example folders...');
console.log('');
const excludes = ['README.md', 'shared'];
const templates = readdirSync(
'./packages/create-docusaurus/templates',
).filter((name) => !excludes.includes(name));
console.log(`Will generate examples for templates: ${templates}`);
templates.forEach(generateTemplateExample);
console.log('Commiting changes');
execSync('git add examples');
execSync("git commit -am 'update examples' --allow-empty");
console.log('');

// update starters
console.log('-------');
console.log('# Updating starter repos and branches ...');
console.log('It can take some time... please wait until done...');
updateStarters();

console.log('');
console.log('-------');
console.log('');
console.log('Generate examples end!');
console.log("Don't forget to push and merge your pull-request!");
console.log('');
const branch = shell.exec('git rev-parse --abbrev-ref HEAD').stdout;
if (branch === 'main') {
throw new Error(
"Please don't generate Docusaurus examples from the main branch!\nWe are going to commit during this process!",
);
}
if (shell.exec('git diff --exit-code').code !== 0) {
throw new Error(
'Please run the generate examples command with a clean Git state and no uncommitted local changes. git diff should display nothing!',
);
}

run();
console.log(`
# Generate examples start!
`);

// delete the examples directories if they exists
console.log(`-------
## Removing example folders...
`);
await fs.rm('./examples/classic', {recursive: true, force: true});
await fs.rm('./examples/classic-typescript', {recursive: true, force: true});
await fs.rm('./examples/facebook', {recursive: true, force: true});

// get the list of all available templates
console.log(`
-------
## Generate example folders...
`);
const excludes = ['README.md', 'shared'];
const templates = (
await fs.readdir('./packages/create-docusaurus/templates')
).filter((name) => !excludes.includes(name));
console.log(`Will generate examples for templates: ${templates.join(',')}`);
// eslint-disable-next-line no-restricted-syntax
for (const template of templates) {
await generateTemplateExample(template);
}
console.log('Commiting changes');
shell.exec('git add examples');
shell.exec("git commit -am 'update examples' --allow-empty");

// update starters
console.log(`
-------
# Updating starter repos and branches ...
It can take some time... please wait until done...
`);
updateStarters();

console.log(`
-------
Generate examples end!
Don't forget to push and merge your pull request!
`);
16 changes: 8 additions & 8 deletions admin/scripts/image-resize.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -5,26 +5,26 @@
* LICENSE file in the root directory of this source tree.
*/

// eslint-disable-next-line import/no-extraneous-dependencies
/* eslint-disable import/no-extraneous-dependencies */

import sharp from 'sharp';
import fs from 'fs/promises';
import fs from 'fs-extra';
import path from 'path';
// eslint-disable-next-line import/no-extraneous-dependencies
import imageSize from 'image-size';
import {fileURLToPath} from 'url';

const allImages = (
await fs.readdir(new URL('../../website/src/data/showcase', import.meta.url))
).filter((file) => ['.png', 'jpg', '.jpeg'].includes(path.extname(file)));

const [,,...selectedImages] = process.argv;
const [, , ...selectedImages] = process.argv;
const images = selectedImages.length > 0 ? selectedImages : allImages;

await Promise.all(
images.map(async (img) => {
const imgPath = new URL(
`../../website/src/data/showcase/${img}`,
import.meta.url,
).pathname;
const imgPath = fileURLToPath(
new URL(`../../website/src/data/showcase/${img}`, import.meta.url),
);
const {width, height} = imageSize(imgPath);
if (width === 640 && height === 320) {
// Do not emit if no resized. Important because we
Expand Down
6 changes: 3 additions & 3 deletions jest.config.js → jest.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* LICENSE file in the root directory of this source tree.
*/

const path = require('path');
import {fileURLToPath} from 'url';

const ignorePatterns = [
'/node_modules/',
Expand All @@ -21,8 +21,8 @@ const ignorePatterns = [
'/packages/docusaurus-migrate/lib',
];

module.exports = {
rootDir: path.resolve(__dirname),
export default {
rootDir: fileURLToPath(new URL('.', import.meta.url)),
verbose: true,
testURL: 'http://localhost/',
testEnvironment: 'node',
Expand Down
12 changes: 6 additions & 6 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
"start:website:baseUrl": "yarn workspace website start:baseUrl",
"start:website:blogOnly": "yarn workspace website start:blogOnly",
"start:website:deployPreview": "cross-env NETLIFY=true CONTEXT='deploy-preview' yarn workspace website start",
"examples:generate": "node generateExamples",
"examples:generate": "node admin/scripts/generateExamples.mjs",
"build": "yarn build:packages && yarn build:website",
"build:packages": "lerna run build --no-private",
"build:website": "yarn workspace website build",
Expand All @@ -41,13 +41,13 @@
"postinstall": "run-p postinstall:**",
"postinstall:main": "yarn lock:update && yarn build:packages",
"postinstall:dev": "is-ci || husky install",
"format": "prettier --config .prettierrc --write \"**/*.{js,jsx,ts,tsx,json}\"",
"format:diff": "prettier --config .prettierrc --list-different \"**/*.{js,jsx,ts,tsx,json}\"",
"format": "prettier --config .prettierrc --write \"**/*.{js,jsx,ts,tsx,json,mjs}\"",
"format:diff": "prettier --config .prettierrc --list-different \"**/*.{js,jsx,ts,tsx,json,mjs}\"",
"format-docs": "prettier --config .prettierrc --write \"**/*.{md,mdx}\"",
"format-docs:diff": "prettier --config .prettierrc --list-different \"**/*.{md,mdx}\"",
"lint": "yarn lint:js && yarn lint:style",
"lint:ci": "yarn lint:js --quiet --report-unused-disable-directives && yarn lint:style",
"lint:js": "eslint --cache \"**/*.{js,jsx,ts,tsx}\"",
"lint:ci": "yarn lint:js --quiet && yarn lint:style",
"lint:js": "eslint --cache --report-unused-disable-directives \"**/*.{js,jsx,ts,tsx,mjs}\"",
"lint:style": "stylelint \"**/*.css\"",
"lerna": "lerna",
"test": "cross-env TZ=UTC jest",
Expand Down Expand Up @@ -116,7 +116,7 @@
"rimraf": "^3.0.2",
"serve": "^12.0.1",
"sharp": "^0.29.1",
"stylelint": "^13.10.0",
"stylelint": "^14.2.0",
"tslib": "^2.3.1",
"typescript": "^4.5.2"
},
Expand Down
2 changes: 1 addition & 1 deletion packages/create-docusaurus/.npmignore
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
copyUntypedFiles.js
copyUntypedFiles.mjs
.tsbuildinfo
__tests__

Expand Down
2 changes: 1 addition & 1 deletion packages/docusaurus-logger/.npmignore
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
copyUntypedFiles.js
copyUntypedFiles.mjs
.tsbuildinfo
tsconfig*
__tests__
2 changes: 1 addition & 1 deletion packages/docusaurus-mdx-loader/.npmignore
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
copyUntypedFiles.js
copyUntypedFiles.mjs
.tsbuildinfo
tsconfig*
__tests__
2 changes: 1 addition & 1 deletion packages/docusaurus-migrate/.npmignore
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
copyUntypedFiles.js
copyUntypedFiles.mjs
.tsbuildinfo
tsconfig*
__tests__
Expand Down
2 changes: 1 addition & 1 deletion packages/docusaurus-plugin-client-redirects/.npmignore
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
copyUntypedFiles.js
copyUntypedFiles.mjs
.tsbuildinfo
tsconfig*
__tests__
2 changes: 1 addition & 1 deletion packages/docusaurus-plugin-content-blog/.npmignore
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
copyUntypedFiles.js
copyUntypedFiles.mjs
.tsbuildinfo
tsconfig*
__tests__
2 changes: 1 addition & 1 deletion packages/docusaurus-plugin-content-docs/.npmignore
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
copyUntypedFiles.js
copyUntypedFiles.mjs
.tsbuildinfo
tsconfig*
__tests__
2 changes: 1 addition & 1 deletion packages/docusaurus-plugin-content-pages/.npmignore
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
copyUntypedFiles.js
copyUntypedFiles.mjs
.tsbuildinfo
tsconfig*
__tests__
2 changes: 1 addition & 1 deletion packages/docusaurus-plugin-debug/.npmignore
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
copyUntypedFiles.js
copyUntypedFiles.mjs
.tsbuildinfo
tsconfig*
__tests__
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,15 @@
* LICENSE file in the root directory of this source tree.
*/

const path = require('path');
const fs = require('fs-extra');
import fs from 'fs-extra';
import {fileURLToPath} from 'url';

/**
* Copy all untyped and static assets files to lib.
*/
const srcDir = path.resolve(__dirname, 'src');
const libDir = path.resolve(__dirname, 'lib');
fs.copySync(srcDir, libDir, {
const srcDir = fileURLToPath(new URL('src', import.meta.url));
const libDir = fileURLToPath(new URL('lib', import.meta.url));
await fs.copy(srcDir, libDir, {
filter(filepath) {
return !/__tests__/.test(filepath) && !/\.tsx?$/.test(filepath);
},
Expand Down
Loading

0 comments on commit 4fad1ce

Please sign in to comment.