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

Add @/ alias and fix config polution #13

Merged
merged 4 commits into from
Nov 22, 2024
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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
* Adds support for `Modules/...` alias for the public builds (Webpack BC).
* Our Vite alias plugin now throws with an useful error message when `Modules/` alias resolver fails.
* Adds sass resolver for `Modules/` alias. It works for both public and private builds in exactly the same way as the JS resolver.
* Adds alias `@/` for all builds, that points to the project build source root. This works for both JS and SCSS.

### Fixes

Expand Down
117 changes: 116 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,120 @@ bundler: 'webpack' // Only visible when using webpack

You can combine these options to precisely control when your component appears. For example, to show a component only when using Vite with HMR active, you would use both `when: 'hmr'` and `bundler: 'vite'`.

## Provided Vite Configuration

While the `apos` build (the code living in the`ui/apos/` directory of every module) is fully preconfigured and doesn't allow for customization, the `public` build (the code imported within `ui/src/` ) is fully customizable and contains a minimal configuration to get you started:
- A PostCSS plugin to handle core features such as "Breakpoint Preview" (when enabled)
- `Modules/` alias to simplify module within the same build
- `@/` alias to allow easy access to cross-module and cross-build source code

### Pre-configured Aliases

The `Modules/` alias is available for both public and admin UI builds and allows you to import modules in your project without worrying about the relative path, but restricts you to only sources inside of `ui/src/` directories.

```javascript
// Current file: modules/another-module/ui/src/index.js
// Actual import path: modules/some-module/ui/src/lib/utils.js
import utils from 'Modules/some-module/lib/utils.js';
```

`@/` alias is available for both public and admin UI builds and allows you to import files from the entire project source code. It follows the same path as your orignal source code, but skips the `ui/` part of the path.

```javascript
// Current file: any file in any module inside of the `ui/` folder
// Actual path: modules/some-module/ui/src/lib/utils.js
import utils from '@/some-module/src/lib/utils.js';

// Actual path: modules/some-module/ui/apos/mixins/SomeMixin.js
import SomeMixin from '@/some-module/apos/mixins/SomeMixin.js';
```

> Warning: You gain access to `public` builds from within the `apos` build, and vice versa, when using the `@/` alias. You should use it with caution, because it might lead to situations where imports are not resolved correctly. This would happen if the imported file (or its deep imports) contains `Modules/` aliased imports. On the other hand, `@/` is more developer friendly, allows auto-completion, and is more intuitive and readable. Be sure to include mostly sources from your current build and ensure no imported sources contain `Modules/` aliased imports when cross-importing from another build.

### Importing Static Assets and Sass

The way we integrate Vite with ApostropheCMS allows now direct imports (including dynamic imports) of assets like images, fonts, and other files. You can import them directly in your vanilla JS/JS framework code:

```javascript
// You can use aliases to import assets or a relative path when in the same module.
// Actual path: modules/some-module/ui/assets/logo.svg
import logo from '@/some-module/assets/logo.svg';
// Logo now cotains the path to the image and will be normallized and correctly
// injected when building the project for production.
```
You can import Sass as well:

```scss
/* You can use aliases to import assets */
/* Actual path: modules/some-module/ui/scss/_styles.scss */
@use '@/some-module/scss/styles';
```

Vue JS supports importing assets directly in the template:

```vue
<template>
<img src="@/some-module/assets/logo.svg" alt="My logo" />
</template>
```

In other frameworks (but also in Vue), you can use the `import` statement to reference the asset:

```jsx
import logo from '@/some-module/assets/logo.svg';

function MyComponent() {
return <img src={logo} alt="My logo" />;
}
```

CSS URL can be resolved in two ways. You can use the documented in the Apostrophe docs `some-module/public` folder and `/modules/some-module/font.ttf` URL where your file is located in `./modules/some-module/public/font.ttf`

```css
@font-face {
font-family: MyFont;
src: url("/modules/some-module/font.ttf") format("truetype");
}
```

Or you can use the absolute sources root path `/src/some-module/fonts/font.ttf` where your file is located in `./modules/some-module/ui/fonts/font.ttf`. You can inspect the sources of your project that are copied in the central location `apos-build/@postrophecms/vite/default` directory. This is the root that Vite uses to resolve the paths and build the project.

```css
@font-face {
font-family: Inter;
src: url("/src/some-module/fonts/font.ttf") format("truetype");
}
```

The same rules apply to paths in the `url()` function in CSS files.

## Configuring Your Code Editor

Every editor, that understands the `jsconfig.json` or `tsconfig.json` file, can be configured to understand the `@/` alias provided by this module. Here is an example of a `jsconfig.json` file that you can place in your project root:

```json
{
"compilerOptions": {
"baseUrl": "./apos-build/@apostrophecms/vite/default",
"paths": {
"@/*": ["./src/*"]
},
"module": "ESNext",
"moduleResolution": "bundler"
},
"exclude": [
"apos-build/@apostrophecms/vite/default/dist",
"node_modules",
"public",
"data"
]
}
```

> Note: If you change your project asset namespace you have to adjust the `baseUrl` and `exclude` path accordingly. For example, if your project namespace is `my-namespace`, the `baseUrl` should be `./apos-build/@apostrophecms/vite/my-namespace` and the `exclude` path - `apos-build/@apostrophecms/vite/my-namespace/dist`.

> Note: If you follow the import in your editor (e.g. Ctrl + Click in VSCode) it will lead to the `apos-build` directory and NOT the original source code. This is because the `apos-build` directory contains a copy of the entire project source code (including Admin UI) from all modules (local and npm) and is the actual source directory used by Vite to build the project.

## Extending the Vite Configuration

You can customize the Vite configuration for your ApostropheCMS project in two ways:
Expand All @@ -171,7 +285,7 @@ You can customize the Vite configuration for your ApostropheCMS project in two w
Use this approach to configure Vite settings within individual ApostropheCMS modules:

```javascript
// modules/my-module/index.js
// modules/some-module/index.js
module.exports = {
build: {
vite: {
Expand Down Expand Up @@ -212,6 +326,7 @@ The configuration format follows the standard [Vite configuration options](https

### Hot Module Replacement
- HMR only monitors existing `anyModule/ui` directories. If you add a new `ui` directory to a module, restart the server to enable HMR for that module. With default ApostropheCMS starter kits using `nodemon`, simply type `rs` in the terminal and press Enter.
- The `apos` HMR won't work when the `public` build contains Vue sources (transformed by the `@vitejs/plugin-vue` plugin). The HMR for the `public` build should still work as expected. The problem is related to the fact that the page would contain two Vue instances (core and reactive) instances, which is not currently supported. We are researching solutions to this issue.

### Public Assets
- Changes to `ui/public` directories don't trigger HMR or page reloads as they require a process restart
Expand Down
21 changes: 11 additions & 10 deletions lib/internals.js
Original file line number Diff line number Diff line change
Expand Up @@ -82,11 +82,10 @@ module.exports = (self) => {

self.printLabels('apos', true);
const { build, config } = await self.getViteBuild('apos', options);
self.printDebug('build-apos', { viteConfig: config });
await build(config);
self.printLabels('apos', false);

self.printDebug('build-apos', { viteConfig: config });

return Date.now();
},

Expand All @@ -104,10 +103,9 @@ module.exports = (self) => {
}
self.printLabels('public', true);
const { build, config } = await self.getViteBuild('public', options);
self.printDebug('build-public', { viteConfig: config });
await build(config);
self.printLabels('public', false);

self.printDebug('build-public', { viteConfig: config });
},

// Create an entrypoint configuration for the vite client.
Expand Down Expand Up @@ -968,12 +966,15 @@ module.exports = (self) => {

// The `apos.vite.config.js` at the project root can be used to extend
// the public config.
const userConfig = (await vite.loadConfigFromFile(
configEnv,
self.userConfigFile,
self.apos.rootDir,
'silent'
))?.config || {};
const userConfig = self.userConfigFile
? (await vite.loadConfigFromFile(
configEnv,
self.userConfigFile,
self.apos.rootDir,
'silent'
))?.config || {}
: {};

merged = vite.mergeConfig(merged, userConfig);

return merged;
Expand Down
7 changes: 6 additions & 1 deletion lib/vite-plugin-apostrophe-alias.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ export default function VitePluginApos({ sourceRoot, id } = {}) {

return {
name: 'vite-plugin-apostrophe-alias',

enforce: 'pre',
config() {
return {
css: {
Expand All @@ -35,6 +35,11 @@ export default function VitePluginApos({ sourceRoot, id } = {}) {
importers: [ { findFileUrl } ]
}
}
},
resolve: {
alias: {
'@': `${sourceRoot}/`
}
}
};
},
Expand Down