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

[v0.36] fix(babel-hooks): Import babel hooks correctly for console, exec and dm up commands #3231

Merged
merged 16 commits into from
Aug 17, 2021
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
10 changes: 2 additions & 8 deletions packages/cli/src/commands/console.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import path from 'path'
import repl from 'repl'

import babelRequireHook from '@babel/register'
import { registerApiSideBabelHook } from '@redwoodjs/internal'

import { getPaths } from '../lib'

Expand All @@ -18,13 +18,7 @@ const mapDBToContext = (ctx) => {

export const handler = () => {
// Transpile on the fly
babelRequireHook({
extends: path.join(paths.base, '.babelrc.js'),
extensions: ['.js', '.ts'],
only: [paths.base],
ignore: ['node_modules'],
cache: false,
})
registerApiSideBabelHook()

const r = repl.start()

Expand Down
30 changes: 13 additions & 17 deletions packages/cli/src/commands/dataMigrate/up.js
Original file line number Diff line number Diff line change
@@ -1,24 +1,15 @@
import fs from 'fs'
import path from 'path'

import babelRequireHook from '@babel/register'
import Listr from 'listr'
import VerboseRenderer from 'listr-verbose-renderer'
import terminalLink from 'terminal-link'

import { registerApiSideBabelHook } from '@redwoodjs/internal'

import { getPaths } from '../../lib'
import c from '../../lib/colors'

babelRequireHook({
dac09 marked this conversation as resolved.
Show resolved Hide resolved
extends: path.join(getPaths().api.base, '.babelrc.js'),
extensions: ['.js', '.ts', '.tsx', '.jsx'],
only: [getPaths().base],
ignore: ['node_modules'],
cache: false,
})

const { db } = require(path.join(getPaths().api.lib, 'db'))

// sorts migrations by date, oldest first
const sortMigrations = (migrations) => {
return migrations.sort((a, b) => {
Expand All @@ -36,7 +27,7 @@ const sortMigrations = (migrations) => {
}

// Return the list of migrations that haven't run against the database yet
const getMigrations = async () => {
const getMigrations = async (db) => {
const basePath = path.join(getPaths().api.dataMigrations)

if (!fs.existsSync(basePath)) {
Expand Down Expand Up @@ -69,7 +60,7 @@ const getMigrations = async () => {
}

// adds data for completed migrations to the DB
const record = async ({ version, name, startedAt, finishedAt }) => {
const record = async (db, { version, name, startedAt, finishedAt }) => {
await db.rW_DataMigration.create({
data: { version, name, startedAt, finishedAt },
})
Expand Down Expand Up @@ -98,7 +89,7 @@ const report = (counters) => {
console.log('')
}

const runScript = async (scriptPath) => {
const runScript = async (db, scriptPath) => {
const script = await import(scriptPath)
const startedAt = new Date()
await script.default({ db })
Expand All @@ -120,7 +111,12 @@ export const builder = (yargs) => {
}

export const handler = async () => {
const migrations = await getMigrations()
// Import babel settings so we can write es6 scripts
registerApiSideBabelHook()

const { db } = require(path.join(getPaths().api.lib, 'db'))

const migrations = await getMigrations(db)

// exit immediately if there aren't any migrations to run
if (!migrations.length) {
Expand All @@ -144,9 +140,9 @@ export const handler = async () => {
},
task: async () => {
try {
const { startedAt, finishedAt } = await runScript(migrationPath)
const { startedAt, finishedAt } = await runScript(db, migrationPath)
counters.run++
await record({
await record(db, {
version,
name: migrationName,
startedAt,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,7 @@ import { files } from '../../../generate/scaffold/scaffold'
import { tasks } from '../scaffold'

jest.mock('fs')
jest.mock('@babel/core', () => {
dac09 marked this conversation as resolved.
Show resolved Hide resolved
return {
transform: () => ({
code: '',
}),
}
})

jest.mock('../../../../lib', () => {
const path = require('path')
return {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,7 @@ import { files } from '../../../generate/scaffold/scaffold'
import { tasks } from '../scaffold'

jest.mock('fs')
jest.mock('@babel/core', () => {
return {
transform: () => ({
code: '',
}),
}
})

jest.mock('../../../../lib', () => {
const path = require('path')
return {
Expand Down
7 changes: 0 additions & 7 deletions packages/cli/src/commands/destroy/sdl/__tests__/sdl.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,6 @@ import { builder, files } from '../../../generate/sdl/sdl'
import { tasks } from '../sdl'

jest.mock('fs')
jest.mock('@babel/core', () => {
return {
transform: () => ({
code: '',
}),
}
})

jest.mock('../../../../lib', () => {
const path = require('path')
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,7 @@ import { builder, files } from '../../../generate/service/service'
import { tasks } from '../service'

jest.mock('fs')
jest.mock('@babel/core', () => {
return {
transform: () => ({
code: '',
}),
}
})

jest.mock('../../../../lib', () => {
const path = require('path')
return {
Expand Down
10 changes: 4 additions & 6 deletions packages/cli/src/commands/exec.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import path from 'path'

import babelRequireHook from '@babel/register'
import Listr from 'listr'
import VerboseRenderer from 'listr-verbose-renderer'
import terminalLink from 'terminal-link'

import { registerApiSideBabelHook } from '@redwoodjs/internal'

import { getPaths } from '../lib'
import c from '../lib/colors'
import { generatePrismaClient } from '../lib/generatePrismaClient'
Expand Down Expand Up @@ -45,9 +46,7 @@ export const handler = async (args) => {
const scriptPath = path.join(getPaths().scripts, name)

// Import babel config for running script
babelRequireHook({
extends: path.join(getPaths().api.base, '.babelrc.js'),
extensions: ['.js', '.ts'],
registerApiSideBabelHook({
plugins: [
[
'babel-plugin-module-resolver',
Expand All @@ -56,10 +55,9 @@ export const handler = async (args) => {
$api: getPaths().api.base,
},
},
'exec-$api-module-resolver',
],
],
ignore: ['node_modules'],
cache: false,
})

try {
Expand Down
7 changes: 1 addition & 6 deletions packages/cli/src/commands/prerender.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import Listr from 'listr'
import VerboseRenderer from 'listr-verbose-renderer'

import { getPaths } from '@redwoodjs/internal'
import { runPrerender, writePrerenderedHtmlFile } from '@redwoodjs/prerender'
import { detectPrerenderRoutes } from '@redwoodjs/prerender/detection'

import c from '../lib/colors'
Expand Down Expand Up @@ -69,12 +70,6 @@ export const getTasks = async (dryrun, routerPathFilter = null) => {
// TODO: Run this automatically at this point.
}

// Import runPrerender async, so babel config et all are only loaded
// when this task runs
const { runPrerender, writePrerenderedHtmlFile } = await import(
'@redwoodjs/prerender'
)

const listrTasks = prerenderRoutes
.filter((route) => route.path)
.flatMap((routeToPrerender) => {
Expand Down
2 changes: 2 additions & 0 deletions packages/internal/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
"dependencies": {
"@babel/parser": "7.15.3",
"@babel/plugin-transform-typescript": "7.15.0",
"@babel/register": "7.15.3",
"@babel/runtime-corejs3": "7.15.3",
"@babel/traverse": "7.15.0",
"@graphql-codegen/cli": "2.0.1",
Expand All @@ -36,6 +37,7 @@
"rimraf": "3.0.2"
},
"devDependencies": {
"@types/babel__core": "7.1.15",
"@types/findup-sync": "4.0.1",
"@types/fs-extra": "9.0.12",
"@types/rimraf": "3.0.1",
Expand Down
2 changes: 1 addition & 1 deletion packages/internal/src/__tests__/build_api.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@ import fs from 'fs'
import path from 'path'

import {
getApiSideBabelConfigPath,
prebuildApiFiles,
cleanApiBuild,
generateProxyFilesForNestedFunction,
} from '../build/api'
import { getApiSideBabelConfigPath } from '../build/babel/api'
import { findApiFiles } from '../files'
import { ensurePosixPath } from '../paths'

Expand Down
66 changes: 8 additions & 58 deletions packages/internal/src/build/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ import rimraf from 'rimraf'
import { findApiFiles } from '../files'
import { ensurePosixPath, getPaths } from '../paths'

import { getApiSideBabelConfigPath, getApiSideBabelPlugins } from './babel/api'

export const buildApi = () => {
// TODO: Be smarter about caching and invalidating files,
// but right now we just delete everything.
Expand Down Expand Up @@ -104,8 +106,8 @@ export const generateProxyFilesForNestedFunction = (prebuiltFile: string) => {
* Remove RedwoodJS "magic" from a user's code leaving JavaScript behind.
*/
export const prebuildApiFiles = (srcFiles: string[]) => {
const plugins = getBabelPlugins()
const rwjsPaths = getPaths()
const plugins = getApiSideBabelPlugins()

return srcFiles.map((srcPath) => {
const relativePathFromSrc = path.relative(rwjsPaths.base, srcPath)
Expand All @@ -128,15 +130,6 @@ export const prebuildApiFiles = (srcFiles: string[]) => {
})
}

export const getApiSideBabelConfigPath = () => {
const p = path.join(getPaths().api.base, 'babel.config.js')
if (fs.existsSync(p)) {
return p
} else {
return false
}
}

// TODO: This can be shared between the api and web sides, but web
// needs to determine plugins on a per-file basis for web side.
export const prebuildFile = (
Expand All @@ -147,8 +140,13 @@ export const prebuildFile = (
plugins: TransformOptions['plugins']
) => {
const code = fs.readFileSync(srcPath, 'utf-8')

// @NOTE
// Even though we specify the config file, babel will still search for .babelrc
// and merge them because we have specified the filename property, unless babelrc = false
const result = transform(code, {
cwd: getPaths().api.base,
babelrc: false,
dac09 marked this conversation as resolved.
Show resolved Hide resolved
filename: srcPath,
configFile: getApiSideBabelConfigPath(),
// we set the sourceFile (for the sourcemap) as a correct, relative path
Expand All @@ -164,54 +162,6 @@ export const prebuildFile = (
return result
}

export const getBabelPlugins = () => {
const rwjsPaths = getPaths()
// Plugin shape: [ ["Target", "Options", "name"] ],
// a custom "name" is supplied so that user's do not accidently overwrite
// Redwood's own plugins.
const plugins: TransformOptions['plugins'] = [
['@babel/plugin-transform-typescript', undefined, 'rwjs-babel-typescript'],
[
require('@redwoodjs/core/dist/babelPlugins/babel-plugin-redwood-src-alias'),
{
srcAbsPath: rwjsPaths.api.src,
},
'rwjs-babel-src-alias',
],
[
require('@redwoodjs/core/dist/babelPlugins/babel-plugin-redwood-directory-named-import'),
undefined,
'rwjs-babel-directory-named-modules',
],
[
'babel-plugin-auto-import',
{
declarations: [
{
// import gql from 'graphql-tag'
default: 'gql',
path: 'graphql-tag',
},
{
// import { context } from '@redwoodjs/api'
members: ['context'],
path: '@redwoodjs/api',
},
],
},
'rwjs-babel-auto-import',
],
// FIXME: Babel plugin GraphQL tag doesn't seem to be working.
['babel-plugin-graphql-tag', undefined, 'rwjs-babel-graphql-tag'],
[
require('@redwoodjs/core/dist/babelPlugins/babel-plugin-redwood-import-dir'),
undefined,
'rwjs-babel-glob-import-dir',
],
].filter(Boolean)
return plugins
}

export const transpileApi = (files: string[], options = {}) => {
const rwjsPaths = getPaths()

Expand Down
Loading