Skip to content

Commit

Permalink
Fixed aliases not working with parameterized imports #48
Browse files Browse the repository at this point in the history
  • Loading branch information
qrac committed Jun 7, 2022
1 parent 58ab1c1 commit dd4db30
Show file tree
Hide file tree
Showing 11 changed files with 86 additions and 97 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "minista",
"description": "Next.js Like Development with 100% Static Generate",
"version": "2.6.1",
"version": "2.6.2",
"bin": {
"minista": "./bin/minista.js"
},
Expand Down
26 changes: 9 additions & 17 deletions src/build.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ import {

import type {
MinistaResolveConfig,
MinistaResolveAlias,
MinistaLocation,
RootStaticContent,
RootEsmContent,
Expand All @@ -30,6 +29,7 @@ import type {
StaticData,
StaticDataItem,
GetStaticData,
AliasArray,
PartialModules,
PartialString,
CssOptions,
Expand All @@ -38,16 +38,14 @@ import type {
import { systemConfig } from "./system.js"
import { getFilePath } from "./path.js"
import {
getEsbuildAlias,
resolvePlugin,
aliasPlugin,
svgrPlugin,
rawPlugin,
partialHydrationPlugin,
} from "./esbuild.js"
import { renderHtml } from "./render.js"
import { slashEnd, reactStylesToString } from "./utils.js"
import { CssModulePlugin } from "./css.js"
import { cssModulePlugin } from "./css.js"

const __filename = url.fileURLToPath(import.meta.url)
const __dirname = path.dirname(__filename)
Expand Down Expand Up @@ -97,14 +95,12 @@ export async function buildTempPages(
buildOptions: {
outBase: string
outDir: string
alias: MinistaResolveAlias
alias: AliasArray
mdxConfig: MdxOptions
svgrOptions: SvgrOptions
cssOptions: CssOptions
}
) {
const alias = getEsbuildAlias([buildOptions.alias])

await esBuild({
entryPoints: entryPoints,
outbase: buildOptions.outBase,
Expand All @@ -121,12 +117,11 @@ export async function buildTempPages(
loader: esbuildLoaders,
plugins: [
resolvePlugin({ "react/jsx-runtime": "react/jsx-runtime.js" }),
aliasPlugin(alias),
CssModulePlugin(buildOptions.cssOptions),
cssModulePlugin(buildOptions.cssOptions, buildOptions.alias),
mdx(buildOptions.mdxConfig),
svgrPlugin(buildOptions.svgrOptions),
rawPlugin(),
partialHydrationPlugin(),
rawPlugin(buildOptions.alias),
partialHydrationPlugin(buildOptions.alias),
],
}).catch(() => process.exit(1))
}
Expand Down Expand Up @@ -638,14 +633,12 @@ export async function buildPartialStringBundle(
entryPoint: string,
buildOptions: {
outFile: string
alias: MinistaResolveAlias
alias: AliasArray
mdxConfig: MdxOptions
svgrOptions: SvgrOptions
cssOptions: CssOptions
}
) {
const alias = getEsbuildAlias([buildOptions.alias])

await esBuild({
entryPoints: [entryPoint],
outfile: buildOptions.outFile,
Expand All @@ -660,11 +653,10 @@ export async function buildPartialStringBundle(
loader: esbuildLoaders,
plugins: [
resolvePlugin({ "react/jsx-runtime": "react/jsx-runtime.js" }),
aliasPlugin(alias),
CssModulePlugin(buildOptions.cssOptions),
cssModulePlugin(buildOptions.cssOptions, buildOptions.alias),
mdx(buildOptions.mdxConfig),
svgrPlugin(buildOptions.svgrOptions),
rawPlugin(),
rawPlugin(buildOptions.alias),
],
}).catch(() => process.exit(1))
}
Expand Down
6 changes: 3 additions & 3 deletions src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import type {
MinistaUserConfig,
MinistaResolveConfig,
MinistaResolveAliasInput,
MinistaResolveAlias,
AliasArray,
} from "./types.js"

import { systemConfig } from "./system.js"
Expand Down Expand Up @@ -131,8 +131,8 @@ export async function mergeConfig(
export async function mergeAlias(
configAlias: MinistaResolveAliasInput,
viteConfigAlias: ViteAliasOptions
): Promise<MinistaResolveAlias> {
const alias: MinistaResolveAlias = []
): Promise<AliasArray> {
const alias: AliasArray = []

async function getAlias(input: MinistaResolveAliasInput | ViteAliasOptions) {
if (!input) {
Expand Down
21 changes: 14 additions & 7 deletions src/css.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,9 @@ import path from "path"
import postcss from "postcss"
import postcssModules from "postcss-modules"

import type { CssOptions } from "./types.js"
import type { AliasArray, CssOptions } from "./types.js"

import { getEsbuildResolvePath } from "./esbuild.js"

enum PreprocessLang {
less = "less",
Expand Down Expand Up @@ -146,27 +148,32 @@ async function buildJs(filepath: string, options: CssOptions) {
return `export default ${classNames};`
}

export function CssModulePlugin(options: CssOptions): Plugin {
export function cssModulePlugin(
options: CssOptions,
alias: AliasArray
): Plugin {
const filter = new RegExp(`\\.module${cssLangs}`)
return {
name: PLUGIN,
setup(build) {
const results = new Map()
build.onResolve({ filter, namespace: "file" }, async (args) => {
if (!options.modules) return args
const sourceFullPath = path.resolve(args.resolveDir, args.path)
if (results.has(sourceFullPath)) return results.get(sourceFullPath)

const content = await buildJs(sourceFullPath, options)
const resolvePath = getEsbuildResolvePath(args, alias)
if (results.has(resolvePath)) return results.get(resolvePath)

const content = await buildJs(resolvePath, options)

const result = {
path: args.path,
path: resolvePath,
namespace: PLUGIN,
pluginData: {
content,
},
}

if (options.modules.cache) results.set(sourceFullPath, result)
if (options.modules.cache) results.set(resolvePath, result)
return result
})

Expand Down
67 changes: 31 additions & 36 deletions src/esbuild.tsx
Original file line number Diff line number Diff line change
@@ -1,26 +1,42 @@
import type { Plugin, PluginBuild } from "esbuild"
import type { Plugin, PluginBuild, OnResolveArgs } from "esbuild"
import type { Config as SvgrOptions } from "@svgr/core"

import fs from "fs-extra"
import path from "path"
import { v4 as uuidv4 } from "uuid"

import type { MinistaResolveAlias } from "./types.js"
import type { AliasObject, AliasArray } from "./types.js"
import { systemConfig } from "./system.js"

export function getEsbuildAlias(aliasArray: MinistaResolveAlias[]) {
const alias = [...aliasArray].flat()
const result: { [key: string]: string } = Object.assign(
export function getEsbuildResolvePath(
args: OnResolveArgs,
alias: AliasArray
): string {
const aliasObject = Object.assign(
{},
...alias.map((item) => ({
[item.find]: item.replacement,
}))
)
return result
function escapeRegExp(find: string) {
return find.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")
}
const aliasKeys = Object.keys(aliasObject)
const aliasReg = new RegExp(
`^(${aliasKeys.map((x) => escapeRegExp(x)).join("|")})`
)
const aliasPath = args.path.replace(aliasReg, function (match) {
return aliasObject[match]
})
const absolutePath = path.isAbsolute(aliasPath)
? aliasPath
: path.join(args.resolveDir, aliasPath)
const replacedPath = absolutePath.replaceAll("\\", "/")
return replacedPath
}

/*! Fork: esbuild-plugin-resolve | https://github.com/markwylde/esbuild-plugin-resolve */
export function resolvePlugin(options: { [key: string]: string }): Plugin {
export function resolvePlugin(alias: AliasObject): Plugin {
function resolvePluginIntercept(
build: PluginBuild,
moduleName: string,
Expand Down Expand Up @@ -57,31 +73,13 @@ export function resolvePlugin(options: { [key: string]: string }): Plugin {
return {
name: "esbuild-resolve",
setup: (build: PluginBuild) => {
for (const moduleName of Object.keys(options)) {
resolvePluginIntercept(build, moduleName, options[moduleName])
for (const moduleName of Object.keys(alias)) {
resolvePluginIntercept(build, moduleName, alias[moduleName])
}
},
}
}

/*! Fork: esbuild-plugin-alias | https://github.com/igoradamenko/esbuild-plugin-alias */
export function aliasPlugin(options: { [key: string]: string }): Plugin {
function escapeRegExp(name: string) {
return name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")
}
const aliases = Object.keys(options)
const re = new RegExp(`^(${aliases.map((x) => escapeRegExp(x)).join("|")})$`)

return {
name: "esbuild-alias",
setup(build) {
build.onResolve({ filter: re }, (args) => ({
path: options[args.path],
}))
},
}
}

/*! Fork: esbuild-plugin-svgr | https://github.com/kazijawad/esbuild-plugin-svgr */
export function svgrPlugin(options: SvgrOptions): Plugin {
return {
Expand All @@ -105,15 +103,14 @@ export function svgrPlugin(options: SvgrOptions): Plugin {
}

/*! Fork: esbuild-plugin-resolve | https://github.com/hannoeru/esbuild-plugin-raw */
export function rawPlugin(): Plugin {
export function rawPlugin(alias: AliasArray): Plugin {
return {
name: "esbuild-raw",
setup(build) {
build.onResolve({ filter: /\?raw$/ }, (args) => {
const resolvePath = getEsbuildResolvePath(args, alias)
return {
path: path.isAbsolute(args.path)
? args.path
: path.join(args.resolveDir, args.path),
path: resolvePath,
namespace: "raw-loader",
}
})
Expand All @@ -130,16 +127,14 @@ export function rawPlugin(): Plugin {
}
}

export function partialHydrationPlugin(): Plugin {
export function partialHydrationPlugin(alias: AliasArray): Plugin {
return {
name: "esbuild-partial-hydration",
setup(build) {
build.onResolve({ filter: /\?ph$/ }, (args) => {
const resolvePath = getEsbuildResolvePath(args, alias)
return {
path: (path.isAbsolute(args.path)
? args.path
: path.join(args.resolveDir, args.path)
).replaceAll("\\", "/"),
path: resolvePath,
namespace: "partial-hydration-loader",
}
})
Expand Down
13 changes: 5 additions & 8 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -175,15 +175,9 @@ export type MinistaResolveConfig = MinistaConfig &
MinistaResolveAliasConfig &
MinistaResolvePathConfig

export type MinistaResolveAliasInput =
| { [key: string]: string }
| { find: string; replacement: string }[]
export type MinistaResolveAlias = {
find: string
replacement: string
}[]
export type MinistaResolveAliasInput = AliasObject | AliasArray
export type MinistaResolveAliasConfig = {
alias: MinistaResolveAlias
alias: AliasArray
}

export type MinistaResolvePathConfig = {
Expand Down Expand Up @@ -282,6 +276,9 @@ export type StaticDataItem = {
export type StaticDataCache = { key: [StaticDataList] } | {}
export type GetStaticData = () => Promise<StaticData>

export type AliasObject = { [key: string]: string }
export type AliasArray = { find: string; replacement: string }[]

export type PartialModules = {
id: string
phId: string
Expand Down
38 changes: 18 additions & 20 deletions test/esbuild.test.ts
Original file line number Diff line number Diff line change
@@ -1,27 +1,25 @@
import type { OnResolveArgs } from "esbuild"

import { describe, expect, it } from "vitest"

import { getEsbuildAlias } from "../src/esbuild"
import { getEsbuildResolvePath } from "../src/esbuild"

describe("getEsbuildAlias", () => {
it("Test: getEsbuildAlias", () => {
const esbuildAlias = [
{
find: "react/jsx-runtime",
replacement: "react/jsx-runtime.js",
},
]
const userAlias = [
{
find: "~",
replacement: "/src",
},
]
const result = getEsbuildAlias([esbuildAlias, userAlias])
describe("getEsbuildResolvePath", () => {
it("Test: getEsbuildResolvePath", () => {
const args: OnResolveArgs = {
path: "~/components/app-header?ph",
importer: "/Users/user/github/demo/src/components/app-layout.tsx",
namespace: "file",
resolveDir: "/Users/user/github/demo/src/components",
kind: "import-statement",
pluginData: undefined,
}
const alias = [{ find: "~", replacement: "/Users/user/github/demo/src" }]
const result = getEsbuildResolvePath(args, alias)

//console.log(result)
expect(result).toEqual({
"react/jsx-runtime": "react/jsx-runtime.js",
"~": "/src",
})
expect(result).toEqual(
"/Users/user/github/demo/src/components/app-header?ph"
)
})
})
4 changes: 2 additions & 2 deletions user/src/components/app-header.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import "./app-header.css"

export const AppHeader = () => {
const AppHeader = () => {
return (
<header>
<img
Expand All @@ -14,4 +14,4 @@ export const AppHeader = () => {
)
}

//export default AppHeader
export default AppHeader
2 changes: 1 addition & 1 deletion user/src/components/app-layout.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { AppHeader } from "~/components/app-header"
import AppHeader from "~/components/app-header?ph"

type AppLayoutProps = {
children: React.ReactNode
Expand Down
2 changes: 1 addition & 1 deletion user/src/pages/css-modules/index.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Head } from "minista"
import style from "../../assets/css-modules/style.module.css"
import style from "~/assets/css-modules/style.module.css"

import AppLayout from "../../components/app-layout"

Expand Down
Loading

0 comments on commit dd4db30

Please sign in to comment.