>  기사  >  웹 프론트엔드  >  Oats~i로 웹 앱 구축 – 설정

Oats~i로 웹 앱 구축 – 설정

PHPz
PHPz원래의
2024-08-19 17:08:07890검색

지난 글에서는 오픈 웹 프레임워크인 Oats~i에 대한 소개 글을 작성했습니다. 핵심 기능, 작동 방식, 기대할 사항에 대해 이야기했습니다. 해당 내용을 읽지 않으셨다면 빨리 읽어보시기 바랍니다.

지난 며칠 동안 프레임워크 설치, 시작 프로젝트 실행, 튜토리얼 및 학습 작업을 원활하게 수행할 수 있도록 Oats~i 관련 몇 가지 도구를 만들었습니다.

이 작품은 Build a Web App with Oats~i 시리즈 중 첫 번째 작품입니다. CLI를 사용하거나 수동으로 두 가지 방법을 사용하여 Oats~i 프로젝트를 설정하는 것부터 시작하겠습니다.

Oats~i CLI 사용(권장)

Oats~i 프로젝트를 설정할 때 가장 권장되는 방법입니다. 상용구 코드를 작성하고 Oats~i 프로젝트를 시작하고 실행하는 데 필요한 종속성을 설치하는 시간을 절약해 줍니다.

그러나 Oats~i와 현재 프로젝트 구조 사이의 잠재적인 파일 충돌을 피하기 위해 완전히 새로운 프로젝트를 생성할 때만 이 방법을 사용해야 합니다.

Cli에는 홈과 정보 페이지가 포함된 시작 프로젝트가 설정되어 있습니다. 이 두 페이지 사이를 탐색하면 Oats~i가 이미 라우팅 및 프래그먼트를 처리하는 작업을 수행하는 모습을 볼 수 있습니다.

Oats~i CLI를 사용하는 방법

  • Oats~i 프로젝트를 생성하려는 폴더로 이동
  • 터미널을 열고 실행하세요.
npx oats-i-cli

  • 안내에 따라 설정이 완료될 때까지 기다립니다
  • 달려라
npm run dev

  • 빌드 시작 시 터미널에 표시된 주소(종종 localhost:8080)로 이동합니다. 그러면 브라우저에서 시작 프로젝트가 열립니다. (로컬 네트워크 주소를 사용하여 동일한 네트워크에 연결된 다른 기기에서 볼 수 있습니다)

수동 설치

Oats~i를 설치하고 싶거나 하드코어한 작업을 좋아하는 기존 프로젝트가 있는 경우 Oats~i를 수동으로 설정할 수 있습니다. 이 프로세스는 훨씬 더 길며 모든 것이 제대로 작동하도록 하려면 더 많은 주의가 필요합니다.

종속성 설치

이제 프로젝트 디렉토리로 이동하여 터미널을 엽니다.

먼저 Oats~i를 빌드하고 실행하는 데 필요한 종속성을 설치합니다. 새로운 프로젝트를 시작한다면 달리기부터 시작하세요.

npm init -y

그런 다음 아래 설명된 단계를 따르세요.

참고: Oats~i 설치 외에도 현재 프로젝트에 라이브러리/종속성이 이미 설치되어 있는 경우 Oats~i 설치 이후의 모든 단계를 건너뛸 수 있습니다.

Oats~i 설치(코어)

핵심 Oats~i 라이브러리를 설치하세요.

달려

npm install oats-i

웹팩 설치

Webpack을 개발 종속성으로 설치합니다. Webpack을 사용하면 라이브러리 처리 모듈 번들링 및 자산 관리를 통해 다른 기능 중에서도 더 나은 프로젝트 구조를 가질 수 있습니다.

달려

npm install --save-dev webpack webpack-cli

Webpack 개발 서버 설치

개발 종속 항목으로 webpack 개발 서버를 설치합니다. 이를 통해 Oats~i 웹 앱을 구축하고 테스트하는 동안 새로운 변경 사항이 자동으로 업데이트되는 개발 서버를 실행할 수 있습니다.

달려

npm install --save-dev webpack-dev-server

핸들바 로더 설치

Oats~i에서 뷰를 렌더링하려면 템플릿 엔진을 사용하는 것이 좋습니다. 내가 선호하는 선택은 핸들바입니다. (핸들바에 대해 자세히 알아보기)

웹팩을 사용하려면 개발 종속성으로 핸들바 로더를 설치해야 합니다. 그러면 핸들바 템플릿을 사용하여 인앱 뷰를 생성하고 렌더링할 수 있습니다.

달려

npm install --save-dev handlebars-loader

HTML 로더 설치

서버측 보기를 생성하기 위해 기본 Oats~i 구성은 html-loader와 html-webpack-plugin의 조합을 사용합니다. 먼저 html-loader 라이브러리를 개발 종속성으로 설치해 보겠습니다.

달려

npm install --save-dev html-loader

HTML-Webpack-플러그인 설치

html-webpack-plugin 라이브러리를 사용하면 webpack을 사용하여 앱에 대한 서버측 보기를 출력할 수 있습니다. html-loader와 함께 작동합니다. 개발 종속성으로 설치하세요.

달려

npm install --save-dev html-webpack-plugin

Babel-Loader 설치

Babel-loader는 webpack을 사용하여 JavaScript 파일을 로드하고 변환합니다. 개발 종속성으로 설치하세요.

달려

npm install --save-dev babel-loader

스타일 로더 및 CSS 로더 설치

스타일 로더 및 css-로더는 html-loader 및 html-webpack-plugin으로 생성된 html 파일에 CSS 가져오기를 스타일시트로 삽입합니다. 개발 종속 항목으로 이러한 로더를 설치하세요.

달려

npm install --save-dev style-loader

npm install --save-dev css-loader

Webpack-Merge 설치

Webpack-merge를 사용하면 여러 webpack 구성 파일을 병합하여 프로젝트 설정에 최적의 방식으로 구성 파일을 구성할 수 있습니다. 이 라이브러리를 개발 종속성으로 설치하세요.

달려

npm install --save-dev webpack-merge

Install Express-Handlebars

Express-handlebars will allow us to emulate server-side rendering in development using handlebars view files outputted by our webpack configuration, using html-loader and html-webpack-plugin. Install this library as a development dependency.

Run

npm install --save-dev express-handlebars

Create Webpack Configuration Files

At the root of your project’s directory, create a new folder and call it “webpack-configs”.

Build a Web App with Oats~i – Setting Up

Navigate into this folder and create two new folders inside it named “main” and “oats~i”.

Your folder structure should now look like this:

Build a Web App with Oats~i – Setting Up

Now, navigate into “oats~i” and create two more folders named “default” and “main”.

Your folder structure should now look like this:

Build a Web App with Oats~i – Setting Up

------

The “default” folder will hold the default webpack configuration needed by Oats~i to have it’s webpack-dependent functions work. Currently, that is code splitting and lazy loading for fragments.

The “main” folder will hold the webpack configuration for loaders used and recommended by Oats~i. These are the loaders we installed in the “install dependencies” stage. Feel free to edit this configuration later if you want to change loaders.

------

Navigate to the “default” folder and create a new file called “webpack.config.js”

Build a Web App with Oats~i – Setting Up

Open the file and paste the following code inside it.

//@ts-check
const DefaultOats_iConfig = {

    optimization: {

        splitChunks: {

            minSize: 0, //Minimum size, in bytes, for a chunk to be generated.
            minSizeReduction: 1, //Minimum size reduction to the main chunk (bundle), in bytes, needed for a chunk to be generated.
            minChunks: 2,
            cacheGroups: {

                commons: {

                    chunks: "async", //Allow chunks to be shared between sync and async
                }
            }
        }
    }
}

module.exports = DefaultOats_iConfig;

Now, navigate back to the “oats~i” folder and navigate into “main”.

Create a new file and name it “webpack.config.js”.

Build a Web App with Oats~i – Setting Up

Open the file and paste the following code inside.

//@ts-check
/**
 * Contains loaders
 */
const DefaultOats_iLoadersConfig = {

    module: {

        rules: [

            {
                test: /\.(html|sv.hbs|p.hbs)$/,
                use: [
                        {
                            loader: "html-loader",
                            options: {
                                minimize: false
                            }
                        }
                ]
            },
            {
                test: /\.(hbs)$/,
                exclude: /\.(sv.hbs|p.hbs)/,
                use: [
                    {
                        loader: "handlebars-loader",
                        options: {
                            inlineRequires: "./assets"
                        }
                    }
                ]
            },
            {
                test: /\.(js)$/,
                exclude: /node_modules/,
                use: [
                    {
                        loader: "babel-loader"
                    }
                ]
            },
            {
                test: /\.(png|svg|jpg|gif)$/,
                type: 'asset/resource',
            },
            {
                test: /\.css$/,
                use: [

                    'style-loader',
                    'css-loader'
                ]
            }
        ]
    }
}

module.exports = DefaultOats_iLoadersConfig;

We’re done setting up the core webpack configuration for Oats~i. Now, we need to merge them in a common configuration file that we’ll use project-wide.

Now, navigate back to the “oats~i” folder then back to the “webpack-configurations” folder. Now navigate into “main”.

Create a new file and name it “webpack.config.js”.

Build a Web App with Oats~i – Setting Up

Open the file and paste the following code inside.

//@ts-check
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const DevServerMiddlewareConfig = require("../../proxy-server/proxy_server");
//The folder we'll have our assets emitted after build
const DIST_PATH_PUBLIC_ASSETS = "../../dist/public";
const { merge } = require("webpack-merge");
const DefaultOats_iConfig = require("../oats~i/default/webpack.config");
const DefaultOats_iLoadersConfig = require("../oats~i/main/webpack.config");

//@ts-expect-error
module.exports = merge(DefaultOats_iConfig, DefaultOats_iLoadersConfig, {

    mode: "development",
    devtool: "eval-source-map",
    output: {

        //Where we'll output public assets
        path: path.resolve(__dirname, `${DIST_PATH_PUBLIC_ASSETS}`),
        publicPath: "/",
        assetModuleFilename: 'assets/[name][ext]',
        filename: "js/[name].dev_bundle.js",
        clean: true
    },
    entry: {

        //The main entry (app)
        index: "./src/app/index/scripts/index.js",
    },
    plugins: [
        new HtmlWebpackPlugin({

            template: "./src/server/home/home.sv.hbs",
            filename: "../views/home.hbs",
            chunks: ["index"],
            minify: false
        })
    ],
    devServer: {

        devMiddleware: {

            writeToDisk: true, //Because of our configured server
        },
        setupMiddlewares: DevServerMiddlewareConfig,
    }
});

Now, we should be done setting up our webpack configurations that’s just fine to run an Oats~i project.

Update package.json

Navigate back to your project’s root folder. Open package.json, look for the “scripts” line, and add the following line after “test” (remember to separate with a comma).

"dev": "webpack-dev-server --config ./webpack-configs/main/webpack.config.js"

Build a Web App with Oats~i – Setting Up

Set Up Dev Server Middlewares

In our final webpack configuration file, we specified a middlewares file for the webpack dev server under

setupMiddlewares: DevServerMiddlewareConfig

Under normal circumstances, you don’t need this setup. You can simply write your server view files in html format, use html-loader and html-webpack-plugin to produce them, and have them directly served by webpack-dev-server during development.

However, as you’ll come to learn later, this is not the best setup for building an Oats~i project that’s already primed for server-side rendering. The server-side files are already in html format, meaning they can’t be easily templated with data before being rendered to the client on the initial request.

To accommodate that, the default Oats~i setup ensures you’re creating template files for your server views that will be easy to render with data from your server every time a client requests for a fresh page.

Our dev server middlewares setup will allow us to mimic such as setup on the actual server, for our development environment.

With its default setup, you don’t need to update it for new fragments that you add to the project, as long as you’re not interested in having them server-side rendered. However, once you get to the point where you want to have server-side rendering and test it in development, setting things up will be much easier and faster, without a change in file formats you’ve already used across the project.

Let’s Set Up this Config

At your project’s root directory, create a new folder and name it “proxy-server”. Inside this new folder, create a file and name it “proxy_server.js”

Build a Web App with Oats~i – Setting Up

Open the file and paste the following code:

//@ts-check
const express = require("express");
const path = require("path");
const hbs = require("express-handlebars");

const DevServerMiddlewareConfig = (middlewares, devServer) => {

    /**
     * @type {import("express").Application}
     */
    const app = devServer.app;

    //Configure the view engine
    app.set("views", path.resolve(__dirname, "../dist/views"));
    app.set("view engine", "hbs");
    app.engine("hbs", hbs.engine({

        extname: "hbs",
        layoutsDir: path.resolve(__dirname, "../dist/views"),
        partialsDir: path.resolve(__dirname, "../dist/views/partials")
    }));

    //for json
    app.use(express.json());
    //I think params and queries
    app.use(express.urlencoded({ extended: false }));
    //static
    app.use(express.static(path.resolve(__dirname, "../dist/public")));

    //My middlewares
    //Capture all
    app.get("/*", (req, res, next) => {

        res.render("home", {
            layout: "home"
        });
    });

    return middlewares;
}

module.exports = DevServerMiddlewareConfig;

This configuration will capture all requests to the dev server and return the home.hbs layout file. You can rename this later to your file’s actual name once you start creating your own Oats~i project and leave it as is as long as you’ll not require server-side rendering for any of your fragments.

Create jsconfig.json

Oats~i is typed using a combination of typescript declaration files and JSDoc. There’s a slight issue where types may not always reflect correctly when using the framework, slightly hurting the developer experience.

Instead of refactoring over 100 files and thousands of lines of code, I’ve found a way to make typescript and intellisense (at least in VSCode) to understand the JSDoc types used in Oats~i.

To do this, navigate to your project’s root folder. Create a file named “jsconfig.json”.

Build a Web App with Oats~i – Setting Up

Open it and paste the code below:

{
    "include": [
        "*/**/*.js",
        "**/*",
        "/**/*",
        "node_modules/oats-i" //to get type definitions for oats-i in your project
    ],
}

NOTE: This bit comes automatically with the cli, so don’t do this for an Oats~i project you’ve set up using the cli.

Create Starter Project Files

Let’s now put everything together and create our starter project files to run an Oats~i app for the first time.

Server-side Base Layout

Navigate to your project’s root folder and create a new folder named “src”. This folder will contain all of our project’s source files.

Inside the “src” folder, create two folders named “app” and “server”.

Build a Web App with Oats~i – Setting Up

Navigate to the “server” folder and create a new folder named “home”. Inside the “home” folder, create a new file and name it “home.sv.hbs”

Build a Web App with Oats~i – Setting Up

Open the file and paste the code below:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Home - My Oats~i App</title>
</head>
<body>
    <app-root id="my-app">
       <div id="nav">
            <a href="/" class="home-link">Home</a>
        </div>
        <main-fragment>
        </main-fragment>
    </app-root>
</body>
</html>

App Files

Now navigate back to “src”. Get into the “app” folder and create two folders name “fragments” and “index”.

Build a Web App with Oats~i – Setting Up

Navigate into the “index” folder and create two folders named “scripts” and “styles”.

Build a Web App with Oats~i – Setting Up

Inside the “scripts” folder, create a new folder called “routing-info”. Inside “routing-info” create two files named “app_main_nav_info.js” and “app_routing_info.js”

Build a Web App with Oats~i – Setting Up

Main Navigation info

Open “app_main_nav_info.js” and paste the following code:

//@ts-check
import MainNavigationInfoBuilder from "oats-i/router/utils/nav-info/main_nav_info_builder";

const AppMainNavInfo = MainNavigationInfoBuilder.buildMainNavigationInfo([
    {
        selector: "home-link",
        defaultRoute: "/",
        baseActiveRoute: "/",
    }
]);

export default AppMainNavInfo;

Main Routing Info

Now open “app_routing_info.js” and paste the following code:

//@ts-check
import RoutingInfoUtils from "oats-i/router/utils/routing-info/routing_info_utils";
import AppMainNavInfo from "./app_main_nav_info";
import homeMainFragmentBuilder from "../../../fragments/home/scripts/home_main_fragment";

const AppRoutingInfo = RoutingInfoUtils.buildMainRoutingInfo([

    {
        route: "/",
        target: homeMainFragmentBuilder,
        nestedChildFragments: null
    }
], AppMainNavInfo);

export default AppRoutingInfo;

Index.css

We’ll create an index.css file for a special reason, which MUST be replicated across all your Oats~i projects if you want consistent behavior.

Navigate back to the “index” folder, and create a new folder named “styles”. Inside the folder, create a new file called “index.css”

Build a Web App with Oats~i – Setting Up

Open the file and paste the following code:

/* Crucial styling to allow specially structured A links to still have clicks intercepted by router. */
/* Carry over to your project */
a *:not([click-override=true]){ 

    pointer-events: none 
}

What this css code does is remove pointer events from elements nested inside an A tag, to ensure the browser doesn’t intercept it before Oats~i does. It also gives you, the developer, the freedom to override this behavior using the attribute click-override=true on any element nested within an A tag.

However, expect Oats~i, at its current state, not to intercept links from an A tag with a child element having that attribute.

This means that you can safely write A tags without any modification or special attributes for Oats~i to automatically intercept them and navigate your app locally. You only add special attributes when you want to stop this behavior and have the browser manually route the website.

Carry over this css directive in all Oats~i projects you create. If you use the cli, you’ll find it already in index.css.

Index.js

Navigate back to “scripts” (inside index) and create a new file named “index.js”.

Build a Web App with Oats~i – Setting Up

Open the file and paste the following code.

//@ts-check
//import styles
import "../styles/index.css";
import AppStateManager from "oats-i/base-history/app_state_manager";
import appRoot from "oats-i/bin/app_root"
import AppRoutingInfo from "./routing-info/app_routing_info";
import MainRouter from "oats-i/router/main_router";
import AppMainNavInfo from "./routing-info/app_main_nav_info";

function initApp(){

    const appStateManager = new AppStateManager(AppRoutingInfo);
    appRoot.initApp(appStateManager, new MainRouter(AppRoutingInfo, appStateManager, (args) => {}, "", async (url) => {

        return {

            canAccess: true,
            fallbackRoute: "/"
        }
    }), { template: null, mainNavInfos: AppMainNavInfo }, "");
}

initApp();

Fragments

Navigate back to the “app” folder. Navigate into “fragments” and create a new folder named “home”.

Inside “home”, create a new folder named “scripts”. Inside “scripts”, create a new file named “home_main_fragment.js”.

Build a Web App with Oats~i – Setting Up

Open the file and paste the code below.

//@ts-check
import AppFragmentBuilder from "oats-i/fragments/builder/AppFragmentBuilder";
import AppMainFragment from "oats-i/fragments/AppMainFragment"

class HomeMainFragment extends AppMainFragment{

    async initializeView(cb){

        //@ts-expect-error cannot find module (for view)
        const uiTemplate = require("../views/home_fragment.hbs")();
        this.onViewInitSuccess(uiTemplate, cb);
    }
}

const homeMainFragmentBuilder = new AppFragmentBuilder(HomeMainFragment, {

    localRoutingInfos: null,
    viewID: "home-main-fragment",
});
export default homeMainFragmentBuilder;

Now navigate back to “home” and create a new folder called “views”. Inside “views”, create a new file and name it “home_fragment.hbs”

Build a Web App with Oats~i – Setting Up

Open file and paste the following code:

<h1>Home Fragment<h1/>

Test the Configuration

Navigate to your project’s root. Open the terminal and run

npm run dev

This will start the webpack-dev-server which will bundle the files and run Oats~i. If you open the browser at the url shown in the terminal (often is localhost:8080) and see a page with “Home Fragment” showing, your project has been successfully set up and Oats~i is working fine.

Configuration Extensibility

Regardless of whether you’ve manually set up an Oats~i project or used the cli, there are configuration flexibilities you can enjoy thanks to Oats~i running on top of Webpack.

Basically, apart from the default Oats~i webpack configuration, you can change anything else to your liking as long as you understand webpack, plugins, and loaders, and how they’ll affect your project.

For instance, you can have a production configuration that will use MiniCssExtractPlugin to extract your css into files that will be added to the final html-webpack-plugin output. You can use advanced babel configurations and even switch handlebars-loader for a loader that suits your favorite templating engine.

However, the default setup provided by Oats~i is good enough for most projects. Later on in the tutorials, we’ll add a new configuration to create the final production build with key features such as minification.

Further Reading

I encourage you to learn about Webpack, why it’s needed, and how you can configure it, to make the most out of Oats~i and other projects you may have using Webpack as a bundler.

Sign Up and Follow for the Next Tutorial

That’s it for setting up Oats~i for your project. If you’re working on a new project, just use the cli. It’s easier, faster, and will directly load you into a beautiful starter project that you can inspect and start getting ideas of how to setup a full project with view, styling, and script files in Oats~I, before we start doing that together.

In the next tutorial, we’ll create our first simple project in Oats~i, where we’ll start learning what routing infos, nav infos, and fragments are in Oats~i.

Leave a like and follow to get notified when the next tutorial drops.

See you then.

Support Oats~i

You can support the development of Oats~i through Patreon or buy me a coffee.

위 내용은 Oats~i로 웹 앱 구축 – 설정의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.