Skip to content

Commit

Permalink
Merge pull request #86 from redwoodjs/pp-add-import-all-macro
Browse files Browse the repository at this point in the history
Add our own `importAll.macro`
  • Loading branch information
peterp authored Jan 28, 2020
2 parents 83807b8 + 3c9286b commit eae31fd
Show file tree
Hide file tree
Showing 16 changed files with 245 additions and 10 deletions.
6 changes: 5 additions & 1 deletion babel.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,9 @@ module.exports = {
['@babel/plugin-proposal-export-default-from'],
['@babel/plugin-proposal-object-rest-spread'],
],
ignore: ['**/*.test.js', '**/__tests__', '**/__mocks__'],
// Only build test files when testing
ignore:
process.env.NODE_ENV == 'test'
? []
: ['**/*.test.', '**/__tests__', '**/__mocks__'],
}
14 changes: 11 additions & 3 deletions packages/core/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,22 @@
"files": [
"dist"
],
"types": "./dist/types.d.ts",
"types": "./dist/main.d.ts",
"license": "MIT",
"dependencies": {
"babel-plugin-macros": "^2.8.0",
"findup-sync": "^4.0.0",
"glob": "^7.1.6",
"toml": "^3.0.0"
},
"devDependencies": {
"@types/findup-sync": "^2.0.2"
"@types/findup-sync": "^2.0.2",
"babel-plugin-tester": "^8.0.1"
},
"jest": {
"testPathIgnorePatterns": [
"/fixtures/"
]
},
"scripts": {
"clean": "rm -rf dist",
Expand All @@ -25,4 +33,4 @@
"test:watch": "yarn test --watch"
},
"gitHead": "ca5de73e28e7f9c034232a2dc5d5e810fcb14a0a"
}
}
10 changes: 10 additions & 0 deletions packages/core/src/__mocks__/paths.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import path from 'path'

const BASE_PATH = path.resolve(__dirname, '../__tests__/fixtures')

export const getPaths = () => ({
api: {
services: path.resolve(BASE_PATH, './api/src/services'),
graphql: path.resolve(BASE_PATH, './api/src/graphql'),
}
})
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP

exports[`macros api.graphql: api.graphql 1`] = `
import importAll from '../importAll.macro.js'
const graphQLImports = importAll('api', 'graphql')
↓ ↓ ↓ ↓ ↓ ↓
import * as _UsersPeterpPersonalRedwoodjsRedwoodPackagesCoreSrc__tests__FixturesApiSrcGraphqlPostsSdlTs from '/Users/peterp/Personal/redwoodjs/redwood/packages/core/src/__tests__/fixtures/api/src/graphql/posts.sdl.ts'
import * as _UsersPeterpPersonalRedwoodjsRedwoodPackagesCoreSrc__tests__FixturesApiSrcGraphqlUsersSdlJs from '/Users/peterp/Personal/redwoodjs/redwood/packages/core/src/__tests__/fixtures/api/src/graphql/users.sdl.js'
const graphQLImports = {
posts: _UsersPeterpPersonalRedwoodjsRedwoodPackagesCoreSrc__tests__FixturesApiSrcGraphqlPostsSdlTs,
users: _UsersPeterpPersonalRedwoodjsRedwoodPackagesCoreSrc__tests__FixturesApiSrcGraphqlUsersSdlJs,
}
`;

exports[`macros api.services: api.services 1`] = `
import importAll from '../importAll.macro.js'
const serviceImports = importAll('api', 'services')
↓ ↓ ↓ ↓ ↓ ↓
import * as _UsersPeterpPersonalRedwoodjsRedwoodPackagesCoreSrc__tests__FixturesApiSrcServicesPostsTs from '/Users/peterp/Personal/redwoodjs/redwood/packages/core/src/__tests__/fixtures/api/src/services/posts.ts'
import * as _UsersPeterpPersonalRedwoodjsRedwoodPackagesCoreSrc__tests__FixturesApiSrcServicesUsersJs from '/Users/peterp/Personal/redwoodjs/redwood/packages/core/src/__tests__/fixtures/api/src/services/users.js'
const serviceImports = {
posts: _UsersPeterpPersonalRedwoodjsRedwoodPackagesCoreSrc__tests__FixturesApiSrcServicesPostsTs,
users: _UsersPeterpPersonalRedwoodjsRedwoodPackagesCoreSrc__tests__FixturesApiSrcServicesUsersJs,
}
`;
Empty file.
Empty file.
Empty file.
Empty file.
24 changes: 24 additions & 0 deletions packages/core/src/__tests__/importAll.macro.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import pluginTester from 'babel-plugin-tester'
import plugin from 'babel-plugin-macros'

const MACRO_IMPORT_PATH = '../importAll.macro.js'

jest.mock('../paths')

pluginTester({
plugin,
snapshot: true,
babelOptions: {
filename: __filename,
},
tests: {
'api.services': `
import importAll from '${MACRO_IMPORT_PATH}'
const serviceImports = importAll('api', 'services')
`,
'api.graphql': `
import importAll from '${MACRO_IMPORT_PATH}'
const graphQLImports = importAll('api', 'graphql')
`,
},
})
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import path from 'path'

import { processPagesDir } from '../src/main'
import { processPagesDir } from '../paths'

describe('paths', () => {
describe('processPagesDir', () => {
it('it accurately finds the pages', () => {
const deps = processPagesDir(
path.resolve(__dirname, '../__mocks__/pages/')
path.resolve(__dirname, './fixtures/web/pages/')
)
expect(deps[0].const).toEqual('AdminMargleTheWorld')
expect(deps[1].const).toEqual('HelloWorld')
Expand Down
76 changes: 76 additions & 0 deletions packages/core/src/importAll.macro.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
import path from 'path'

import { createMacro } from 'babel-plugin-macros'
import glob from 'glob'

import { getPaths } from './paths'

// The majority of this code is copied from `importAll.macro`: https://github.com/kentcdodds/import-all.macro
// And was modified to work with our `getPaths`.

/**
* This macro runs during build time.
* @example
* ```js
* import importAll from '@redwoodjs/core/importAll.macro
* const typeDefs = importAll('api', 'graphql')
* ```
*/
function prevalMacros({ references, state, babel }) {
references.default.forEach((referencePath) => {
if (referencePath.parentPath.type === 'CallExpression') {
importAll({ referencePath, state, babel })
} else {
throw new Error(
`This is not supported: \`${referencePath
.findParent(babel.types.isExpression)
.getSource()}\`. Please use "importAll('target', 'directory')"`
)
}
})
}

const getGlobPattern = (callExpressionPath) => {
const redwoodPaths = getPaths()
const args = callExpressionPath.parentPath.get('arguments')
const target = args[0].evaluate().value
const dir = args[1].evaluate().value
return `${redwoodPaths[target][dir]}/*.{ts,js}`
}

function importAll({ referencePath, state, babel }) {
const t = babel.types
const globPattern = getGlobPattern(referencePath)
// Grab a list of the files
const importSources = glob.sync(globPattern)

const { importNodes, objectProperties } = importSources.reduce(
(all, source) => {
const id = referencePath.scope.generateUidIdentifier(source)
all.importNodes.push(
t.importDeclaration(
[t.importNamespaceSpecifier(id)],
t.stringLiteral(source)
)
)

// Turn `./relativePath/a.js` into `a`.
const objectKey = path
.basename(source, path.extname(source))
.replace('.sdl', '')
all.objectProperties.push(
t.objectProperty(t.stringLiteral(objectKey), id)
)
return all
},
{ importNodes: [], objectProperties: [] }
)

const program = state.file.path
program.node.body.unshift(...importNodes)

const objectExpression = t.objectExpression(objectProperties)
referencePath.parentPath.replaceWith(objectExpression)
}

export default createMacro(prevalMacros)
File renamed without changes.
14 changes: 11 additions & 3 deletions packages/core/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,18 @@
"esModuleInterop": true,
"baseUrl": ".",
"paths": {
"src/*": ["src/*"]
"src/*": [
"src/*"
]
},
"declaration": true,
"declarationDir": "./dist"
},
"include": ["src"]
}
"include": [
"src"
],
"exclude": [
"**/__tests__",
"**/__mocks__"
]
}
72 changes: 71 additions & 1 deletion yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -1744,6 +1744,13 @@
dependencies:
regenerator-runtime "^0.13.2"

"@babel/runtime@^7.6.3", "@babel/runtime@^7.7.2":
version "7.8.3"
resolved "https://registry.yarnpkg.com/@babel/runtime/-/runtime-7.8.3.tgz#0811944f73a6c926bb2ad35e918dcc1bfab279f1"
integrity sha512-fVHx1rzEmwB130VTkLnxR+HmxcTjGzH12LYQcFFoBwakMd3aOMD4OsRN7tGG/UOYE2ektgFrS8uACAoRk1CY0w==
dependencies:
regenerator-runtime "^0.13.2"

"@babel/template@^7.7.4":
version "7.7.4"
resolved "https://registry.yarnpkg.com/@babel/template/-/template-7.7.4.tgz#428a7d9eecffe27deac0a98e23bf8e3675d2a77b"
Expand Down Expand Up @@ -3258,6 +3265,11 @@
resolved "https://registry.yarnpkg.com/@types/normalize-package-data/-/normalize-package-data-2.4.0.tgz#e486d0d97396d79beedd0a6e33f4534ff6b4973e"
integrity sha512-f5j5b/Gf71L+dbqxIpQ4Z2WlmI/mPJ0fOkGGmFgtb6sAu97EPczzbS3/tJKxmcYDj55OX6ssqwDAWOHIYDRDGA==

"@types/parse-json@^4.0.0":
version "4.0.0"
resolved "https://registry.yarnpkg.com/@types/parse-json/-/parse-json-4.0.0.tgz#2f8bb441434d163b35fb8ffdccd7138927ffb8c0"
integrity sha512-//oorEZjL6sbPcKUaCdIGlIUeH26mgzimjBB77G6XRgnDl/L5wOnpyBGRe/Mmf5CVW3PwEBE1NjiMZ/ssFh4wA==

"@types/prop-types@*":
version "15.7.3"
resolved "https://registry.yarnpkg.com/@types/prop-types/-/prop-types-15.7.3.tgz#2ab0d5da2e5815f94b0b9d4b95d1e5f243ab2ca7"
Expand Down Expand Up @@ -4300,6 +4312,15 @@ babel-plugin-jest-hoist@^25.1.0:
dependencies:
"@types/babel__traverse" "^7.0.6"

babel-plugin-macros@^2.8.0:
version "2.8.0"
resolved "https://registry.yarnpkg.com/babel-plugin-macros/-/babel-plugin-macros-2.8.0.tgz#0f958a7cc6556b1e65344465d99111a1e5e10138"
integrity sha512-SEP5kJpfGYqYKpBrj5XU3ahw5p5GOHJ0U5ssOSQ/WBVdwkD2Dzlce95exQTs3jOVWPPKLBN2rlEWkCK7dSmLvg==
dependencies:
"@babel/runtime" "^7.7.2"
cosmiconfig "^6.0.0"
resolve "^1.12.0"

babel-plugin-module-resolver@^3.2.0:
version "3.2.0"
resolved "https://registry.yarnpkg.com/babel-plugin-module-resolver/-/babel-plugin-module-resolver-3.2.0.tgz#ddfa5e301e3b9aa12d852a9979f18b37881ff5a7"
Expand All @@ -4322,6 +4343,15 @@ babel-plugin-module-resolver@^4.0.0:
reselect "^4.0.0"
resolve "^1.13.1"

babel-plugin-tester@^8.0.1:
version "8.0.1"
resolved "https://registry.yarnpkg.com/babel-plugin-tester/-/babel-plugin-tester-8.0.1.tgz#6cffa9b9d508a567139339afc74c97c64b62f131"
integrity sha512-5PN7FR1oxbTiA7JUdInT+vFkgu6ckYL5moRzWf5T7hAq+QX5cbcHpoXNHu1x7SQHCEZwYMhN1HzZoqeolNaO2g==
dependencies:
lodash.mergewith "^4.6.2"
prettier "^1.19.1"
strip-indent "^3.0.0"

babel-preset-jest@^25.1.0:
version "25.1.0"
resolved "https://registry.yarnpkg.com/babel-preset-jest/-/babel-preset-jest-25.1.0.tgz#d0aebfebb2177a21cde710996fce8486d34f1d33"
Expand Down Expand Up @@ -5407,6 +5437,17 @@ cosmiconfig@^5.1.0:
js-yaml "^3.13.1"
parse-json "^4.0.0"

cosmiconfig@^6.0.0:
version "6.0.0"
resolved "https://registry.yarnpkg.com/cosmiconfig/-/cosmiconfig-6.0.0.tgz#da4fee853c52f6b1e6935f41c1a2fc50bd4a9982"
integrity sha512-xb3ZL6+L8b9JLLCx3ZdoZy4+2ECphCMo2PwqgP1tlfVq6M6YReyzBJtvWWtbDSpNr9hn96pkCiZqUcFEc+54Qg==
dependencies:
"@types/parse-json" "^4.0.0"
import-fresh "^3.1.0"
parse-json "^5.0.0"
path-type "^4.0.0"
yaml "^1.7.2"

create-ecdh@^4.0.0:
version "4.0.3"
resolved "https://registry.yarnpkg.com/create-ecdh/-/create-ecdh-4.0.3.tgz#c9111b6f33045c4697f144787f9254cdc77c45ff"
Expand Down Expand Up @@ -7841,7 +7882,7 @@ import-fresh@^2.0.0:
caller-path "^2.0.0"
resolve-from "^3.0.0"

import-fresh@^3.0.0:
import-fresh@^3.0.0, import-fresh@^3.1.0:
version "3.2.1"
resolved "https://registry.yarnpkg.com/import-fresh/-/import-fresh-3.2.1.tgz#633ff618506e793af5ac91bf48b72677e15cbe66"
integrity sha512-6e1q1cnWP2RXD9/keSkxHScg508CdXqXWgWBaETNhyuBFz+kUZlKboh+ISK+bU++DmbHimVBrOz/zzPe0sZ3sQ==
Expand Down Expand Up @@ -9231,6 +9272,11 @@ lodash.merge@^4.6.2:
resolved "https://registry.yarnpkg.com/lodash.merge/-/lodash.merge-4.6.2.tgz#558aa53b43b661e1925a0afdfa36a9a1085fe57a"
integrity sha512-0KpjqXRVvrYyCsX1swR/XTK0va6VQkQM6MNo7PqW77ByjAhoARA8EfrP1N4+KlKj8YS0ZUCtRT/YUuhyYDujIQ==

lodash.mergewith@^4.6.2:
version "4.6.2"
resolved "https://registry.yarnpkg.com/lodash.mergewith/-/lodash.mergewith-4.6.2.tgz#617121f89ac55f59047c7aec1ccd6654c6590f55"
integrity sha512-GK3g5RPZWTRSeLSpgP8Xhra+pnjBC56q9FZYe1d5RN3TJ35dbkGy3YqBSMbyCrlbi+CM9Z3Jk5yTL7RCsqboyQ==

lodash.set@^4.3.2:
version "4.3.2"
resolved "https://registry.yarnpkg.com/lodash.set/-/lodash.set-4.3.2.tgz#d8757b1da807dde24816b0d6a84bea1a76230b23"
Expand Down Expand Up @@ -9616,6 +9662,11 @@ mimic-response@^1.0.0, mimic-response@^1.0.1:
resolved "https://registry.yarnpkg.com/mimic-response/-/mimic-response-1.0.1.tgz#4923538878eef42063cb8a3e3b0798781487ab1b"
integrity sha512-j5EctnkH7amfV/q5Hgmoal1g2QHFJRraOtmx0JpIqkxhBhI/lJSl1nMpQ45hVarwNETOoWEimndZ4QK0RHxuxQ==

min-indent@^1.0.0:
version "1.0.0"
resolved "https://registry.yarnpkg.com/min-indent/-/min-indent-1.0.0.tgz#cfc45c37e9ec0d8f0a0ec3dd4ef7f7c3abe39256"
integrity sha1-z8RcN+nsDY8KDsPdTvf3w6vjklY=

mini-css-extract-plugin@^0.8.0:
version "0.8.2"
resolved "https://registry.yarnpkg.com/mini-css-extract-plugin/-/mini-css-extract-plugin-0.8.2.tgz#a875e169beb27c88af77dd962771c9eedc3da161"
Expand Down Expand Up @@ -10707,6 +10758,11 @@ path-type@^3.0.0:
dependencies:
pify "^3.0.0"

path-type@^4.0.0:
version "4.0.0"
resolved "https://registry.yarnpkg.com/path-type/-/path-type-4.0.0.tgz#84ed01c0a7ba380afe09d90a8c180dcd9d03043b"
integrity sha512-gDKb8aZMDeD/tZWs9P6+q0J9Mwkdl6xMV8TjnGP3qJVJ06bdMgkbBlLU8IdfOsIsFz2BW1rNVT3XuNEl8zPAvw==

pbkdf2@^3.0.3:
version "3.0.17"
resolved "https://registry.yarnpkg.com/pbkdf2/-/pbkdf2-3.0.17.tgz#976c206530617b14ebb32114239f7b09336e93a6"
Expand Down Expand Up @@ -12508,6 +12564,13 @@ strip-indent@^2.0.0:
resolved "https://registry.yarnpkg.com/strip-indent/-/strip-indent-2.0.0.tgz#5ef8db295d01e6ed6cbf7aab96998d7822527b68"
integrity sha1-XvjbKV0B5u1sv3qrlpmNeCJSe2g=

strip-indent@^3.0.0:
version "3.0.0"
resolved "https://registry.yarnpkg.com/strip-indent/-/strip-indent-3.0.0.tgz#c32e1cee940b6b3432c771bc2c54bcce73cd3001"
integrity sha512-laJTa3Jb+VQpaC6DseHhF7dXVqHTfJPCRDaEbid/drOhgitgYku/letMUqOXFoWV0zIIUbjpdH2t+tYj4bQMRQ==
dependencies:
min-indent "^1.0.0"

strip-json-comments@^3.0.1:
version "3.0.1"
resolved "https://registry.yarnpkg.com/strip-json-comments/-/strip-json-comments-3.0.1.tgz#85713975a91fb87bf1b305cca77395e40d2a64a7"
Expand Down Expand Up @@ -13802,6 +13865,13 @@ yallist@^4.0.0:
resolved "https://registry.yarnpkg.com/yallist/-/yallist-4.0.0.tgz#9bb92790d9c0effec63be73519e11a35019a3a72"
integrity sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==

yaml@^1.7.2:
version "1.7.2"
resolved "https://registry.yarnpkg.com/yaml/-/yaml-1.7.2.tgz#f26aabf738590ab61efaca502358e48dc9f348b2"
integrity sha512-qXROVp90sb83XtAoqE8bP9RwAkTTZbugRUTm5YeFCBfNRPEp2YzTeqWiz7m5OORHzEvrA/qcGS8hp/E+MMROYw==
dependencies:
"@babel/runtime" "^7.6.3"

yargs-parser@^10.0.0:
version "10.1.0"
resolved "https://registry.yarnpkg.com/yargs-parser/-/yargs-parser-10.1.0.tgz#7202265b89f7e9e9f2e5765e0fe735a905edbaa8"
Expand Down

0 comments on commit eae31fd

Please sign in to comment.