Skip to main content

Ionic JavaScript 快速入门

欢迎!本指南将带你了解使用 Vite 进行 Ionic JavaScript 开发的基础知识。你将学习如何设置开发环境、创建一个简单的项目、探索项目结构,并了解 Ionic 组件的工作原理。这非常适合在构建你的第一个真实应用之前熟悉 Ionic JavaScript。

🌐 Welcome! This guide will walk you through the basics of Ionic JavaScript development using Vite. You'll learn how to set up your development environment, create a simple project, explore the project structure, and understand how Ionic components work. This is perfect for getting familiar with Ionic JavaScript before building your first real app.

如果你想了解 Ionic JavaScript 的概况以及它在网络开发生态系统中的作用,请参见 Ionic JavaScript 概览

🌐 If you're looking for a high-level overview of what Ionic JavaScript is and how it fits into the web development ecosystem, see the Ionic JavaScript Overview.

先决条件

🌐 Prerequisites

在开始之前,确保你的计算机上已安装 Node.js 和 npm。你可以通过运行以下命令来检查:

🌐 Before you begin, make sure you have Node.js and npm installed on your machine. You can check by running:

node -v
npm -v

如果你没有 Node.js 和 npm,请在此下载 Node.js(其中包含 npm)。

🌐 If you don't have Node.js and npm, download Node.js here (which includes npm).

使用 Vite 创建项目

🌐 Create a Project with Vite

首先,使用普通 JavaScript 创建一个新的 Vite 项目:

🌐 First, create a new Vite project with vanilla JavaScript:

npm create vite@latest my-app -- --template vanilla

cd my-app

安装项目依赖和 Ionic 核心:

🌐 Install the project dependencies and Ionic Core:

npm install
npm install @ionic/core

安装完成后,启动开发服务器:

🌐 After installation, start the development server:

npm run dev

打开你的浏览器并访问控制台显示的 URL。

🌐 Open your browser and visit the URL shown in the console.

探索项目结构

🌐 Explore the Project Structure

你的新应用的目录将如下所示:

🌐 Your new app's directory will look like this:

├── index.html
└── src/
├── counter.js
├── main.js
└── style.css
删除文件

counter.jsstyle.css 文件可以删除。我们不会使用它们。

info

下面示例中的所有文件路径都是相对于项目根目录的。

让我们配置项目,初始化 Ionic,并添加组件以创建我们的应用。

🌐 Let's configure the project, initialize Ionic, and add components to create our app.

配置 Vite

🌐 Configure Vite

安装 vite-plugin-static-copy 包:

🌐 Install the vite-plugin-static-copy package:

npm install vite-plugin-static-copy --save-dev

在项目根目录添加一个 vite.config.js 文件,内容如下:

🌐 Add a vite.config.js file at the project root with the following:

vite.config.js
import { defineConfig } from 'vite';
import { viteStaticCopy } from 'vite-plugin-static-copy';

export default defineConfig({
optimizeDeps: {
exclude: ['@ionic/core'],
},
build: {
rollupOptions: {
output: {
manualChunks: undefined,
},
external: ['/ionic.esm.js'],
},
},
plugins: [
viteStaticCopy({
targets: [
{
src: 'node_modules/@ionic/core/dist/ionic/*',
dest: '',
},
],
}),
],
});

这会复制 Capacitor 在使用懒加载的 Ionic 组件时所需的 Ionic 文件。

🌐 This copies the necessary Ionic files that Capacitor will need to work with lazy loaded Ionic components.

初始化 Ionic

🌐 Initialize Ionic

main.js 的内容替换为以下内容:

🌐 Replace the contents of main.js with the following:

src/main.js
// Load Ionic
(async () => {
// Set the path to a variable to
// prevent Vite from analyzing in dev
const ionicPath = '/ionic.esm.js';
await import(/* @vite-ignore */ ionicPath);
})();

// Core CSS required for Ionic components to work properly
import '@ionic/core/css/core.css';

// Basic CSS for apps built with Ionic
import '@ionic/core/css/normalize.css';
import '@ionic/core/css/structure.css';
import '@ionic/core/css/typography.css';

// Optional CSS utils that can be commented out
import '@ionic/core/css/padding.css';
import '@ionic/core/css/float-elements.css';
import '@ionic/core/css/text-alignment.css';
import '@ionic/core/css/text-transformation.css';
import '@ionic/core/css/flex-utils.css';
import '@ionic/core/css/display.css';

这根据环境初始化 Ionic,然后导入所有可用的 CSS 文件。

🌐 This initializes Ionic based on the environment and then imports all of the available CSS files.

添加应用组件

🌐 Add the App Component

更新你的 index.html 来配置元数据并使用 Ionic 组件:

🌐 Update your index.html to configure the metadata and use Ionic components:

index.html
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta
name="viewport"
content="viewport-fit=cover, width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no"
/>
<title>my-app</title>
</head>
<body>
<ion-app>
<ion-router>
<ion-route url="/" component="home-page"></ion-route>
<ion-route url="/new" component="new-page"></ion-route>
</ion-router>
<ion-router-outlet></ion-router-outlet>
</ion-app>

<script type="module" src="/src/main.js"></script>
</body>
</html>

这设置了应用的根,使用了 Ionic 的 ion-appion-routerion-router-outlet 组件。关键的变化是将默认的 <div id="app"> 替换为 Ionic 的路由和布局组件。路由出口是显示页面的地方。

🌐 This sets up the root of your application, using Ionic's ion-app, ion-router, and ion-router-outlet components. The key change is replacing the default <div id="app"> with Ionic's routing and layout components. The router outlet is where your pages will be displayed.

查看路由

🌐 View Routes

路由在 index.html 中使用 ion-route 组件定义在 ion-router 内部:

🌐 Routes are defined in the index.html using ion-route components inside the ion-router:

index.html
<ion-router>
<ion-route url="/" component="home-page"></ion-route>
<ion-route url="/new" component="new-page"></ion-route>
</ion-router>

当你访问根 URL (/) 时,home-page 组件将被加载。当你访问 /new URL 时,new-page 组件将被加载。接下来我们将定义这些组件。

🌐 When you visit the root URL (/), the home-page component will be loaded. When you visit the /new URL, the new-page component will be loaded. We will define these components next.

添加主页

🌐 Add the Home Page

src 文件夹内创建一个名为 pages 的新目录,然后在该目录中添加一个名为 HomePage.js 的文件,内容如下:

🌐 Create a new directory called pages inside the src folder, then add a file called HomePage.js in that directory with the following content:

src/pages/HomePage.js
class HomePage extends HTMLElement {
connectedCallback() {
this.innerHTML = `
<ion-header>
<ion-toolbar>
<ion-title>Blank</ion-title>
</ion-toolbar>
</ion-header>
<ion-content class="ion-padding">
<div id="container">
<strong>Ready to create an app?</strong>
<p>
Start with Ionic
<a target="_blank" rel="noopener noreferrer" href="https://ionic.nodejs.cn/components">UI Components</a>
</p>
</div>
</ion-content>
`;
}
}

customElements.define('home-page', HomePage);

这会创建一个名为 home-page 的自定义元素,它包含你的主页布局。该页面使用 Ionic 的布局组件来创建带有工具栏的页眉和可滚动的内容区域。

🌐 This creates a custom element called home-page that contains the layout for your Home page. The page uses Ionic's layout components to create a header with a toolbar and scrollable content area.

了解更多

有关 Ionic 布局组件的详细信息,请参阅 HeaderToolbarTitleContent 文档。

接下来,在 index.html 中的 main.js 导入之前添加一个 <script> 标签以导入首页:

🌐 Next, add a <script> tag before the main.js import in index.html to import the Home page:

index.html
<script type="module">
import './src/pages/HomePage.js';
</script>

<script type="module" src="/src/main.js"></script>

此时,你的浏览器应显示主页。

🌐 At this point your browser should be displaying the Home page.

Screenshot of the Ionic Core Home page

添加一个 Ionic 组件

🌐 Add an Ionic Component

你可以通过更多的 Ionic UI 组件来增强你的首页。例如,添加一个 按钮 来导航到另一个页面。更新 HomePage.js 中的 HomePage 组件:

🌐 You can enhance your Home page with more Ionic UI components. For example, add a Button to navigate to another page. Update the HomePage component in HomePage.js:

src/pages/HomePage.js
class HomePage extends HTMLElement {
connectedCallback() {
this.innerHTML = `
<ion-header>
<ion-toolbar>
<ion-title>Blank</ion-title>
</ion-toolbar>
</ion-header>
<ion-content class="ion-padding">
<div id="container">
<strong>Ready to create an app?</strong>
<p>
Start with Ionic
<a target="_blank" rel="noopener noreferrer" href="https://ionic.nodejs.cn/components">UI Components</a>
</p>
</div>

<ion-button>Navigate</ion-button>
</ion-content>
`;
}
}

customElements.define('home-page', HomePage);

添加新页面

🌐 Add a New Page

src/pages 添加名为 NewPage.js 的新文件,内容如下:

🌐 Add a new file named NewPage.js to src/pages with the following content:

src/pages/NewPage.js
class NewPage extends HTMLElement {
connectedCallback() {
this.innerHTML = `
<ion-header>
<ion-toolbar>
<ion-buttons slot="start">
<ion-back-button default-href="/"></ion-back-button>
</ion-buttons>
<ion-title>New</ion-title>
</ion-toolbar>
</ion-header>
<ion-content class="ion-padding">
<h2>Welcome to the new page!</h2>
</ion-content>
`;
}
}

customElements.define('new-page', NewPage);

这将创建一个带有 返回按钮 的页面,该按钮位于 工具栏 中。返回按钮将自动处理返回到上一页的导航,如果没有历史记录,则返回到 /

🌐 This creates a page with a Back Button in the Toolbar. The back button will automatically handle navigation back to the previous page, or to / if there is no history.

接下来,更新 index.html 文件中导入主页的 <script> 标签,以便也导入新页面:

🌐 Next, update the <script> tag which imports the Home page in the index.html file to also import the New page:

index.html
<script type="module">
import './src/pages/HomePage.js';
import './src/pages/NewPage.js';
</script>

🌐 Navigate to the New Page

要导航到新页面,将 HomePage.js 中的按钮更新为位于 ion-router-link 内:

🌐 To navigate to the new page, update the button in HomePage.js to be inside of an ion-router-link:

src/pages/HomePage.js
<ion-router-link href="/new">
<ion-button>Navigate</ion-button>
</ion-router-link>

当按钮被点击时,Ionic 的路由会自动导航到 /new 路由并显示 new-page 组件。

🌐 When the button is clicked, Ionic's router will automatically navigate to the /new route and display the new-page component.

info

导航也可以使用 document.querySelector('ion-router').push('/new') 通过编程方式执行。更多信息请参阅 Ionic 路由文档

将图标添加到新页面

🌐 Add Icons to the New Page

Ionic JavaScript 自带 Ionicons 支持。要使用图标,你需要导入它们,用 addIcons 注册它们,然后使用 ion-icon 组件来使用它们。

🌐 Ionic JavaScript comes with Ionicons support. To use icons, you need to import them, register them with addIcons, and then use them with the ion-icon component.

添加必要的导入并在 main.js 中注册图标:

🌐 Add the necessary imports and register the icons in main.js:

src/main.js
// ...Ionic initialization

// Icon imports
import { addIcons } from 'ionicons';
import { heart, logoIonic } from 'ionicons/icons';

addIcons({ heart, logoIonic });

// ...CSS imports

接下来,更新 NewPage.js 以包含这些图标:

🌐 Next, update NewPage.js to include the icons:

src/pages/NewPage.js
class NewPage extends HTMLElement {
connectedCallback() {
this.innerHTML = `
<ion-header>
<ion-toolbar>
<ion-buttons slot="start">
<ion-back-button default-href="/"></ion-back-button>
</ion-buttons>
<ion-title>New</ion-title>
</ion-toolbar>
</ion-header>
<ion-content class="ion-padding">
<h2>Welcome to the new page!</h2>

<ion-icon name="heart"></ion-icon>
<ion-icon name="logo-ionic"></ion-icon>
</ion-content>
`;
}
}

customElements.define('new-page', NewPage);

欲了解更多信息,请参阅 Icon 文档Ionicons 文档

🌐 For more information, see the Icon documentation and the Ionicons documentation.

调用组件方法

🌐 Call Component Methods

让我们添加一个可以将内容区域滚动到底部的按钮。更新 NewPage.js 以包括可滚动的内容和滚动按钮:

🌐 Let's add a button that can scroll the content area to the bottom. Update NewPage.js to include scrollable content and a scroll button:

src/pages/NewPage.js
class NewPage extends HTMLElement {
connectedCallback() {
this.innerHTML = `
<ion-header>
<ion-toolbar>
<ion-buttons slot="start">
<ion-back-button default-href="/"></ion-back-button>
</ion-buttons>
<ion-title>New</ion-title>
</ion-toolbar>
</ion-header>
<ion-content class="ion-padding">
<h2>Welcome to the new page!</h2>

<ion-icon name="heart"></ion-icon>
<ion-icon name="logo-ionic"></ion-icon>

<ion-button id="scroll-btn">Scroll to Bottom</ion-button>


<div id="item-list"></div>
</ion-content>
`;

// Generate items and add scroll functionality after the element is connected
this.setupScrolling();
}

setupScrolling() {
// Wait for ion-content to be ready
customElements.whenDefined('ion-content').then(() => {
// Generate items
const itemList = this.querySelector('#item-list');
for (let i = 1; i <= 50; i++) {
const item = document.createElement('ion-item');
const label = document.createElement('ion-label');
label.textContent = `Item ${i}`;
item.appendChild(label);
itemList.appendChild(item);
}

// Add scroll functionality
const scrollBtn = this.querySelector('#scroll-btn');
const content = this.querySelector('ion-content');

if (scrollBtn && content) {
scrollBtn.addEventListener('click', () => {
content.scrollToBottom(300);
});
}
});
}
}

customElements.define('new-page', NewPage);

调用 Ionic 组件的方法:

🌐 To call methods on Ionic components:

  1. 使用 querySelector 获取组件元素的引用
  2. 直接在元素上调用方法

你可以在它们的 API 文档的 方法 部分找到每个组件的可用方法。

🌐 You can find available methods for each component in the Methods section of their API documentation.

在设备上运行

🌐 Run on a Device

Ionic 的组件无处不在:在 iOS、Android 和 PWA 上都能使用。要部署到移动端,请使用 Capacitor

🌐 Ionic's components work everywhere: on iOS, Android, and PWAs. To deploy to mobile, use Capacitor:

npm install @capacitor/core @capacitor/cli @capacitor/ios @capacitor/android
npx cap init

npm run build

npx cap add ios
npx cap add android

在它们的 IDE 中打开本地项目:

🌐 Open the native projects in their IDEs:

npx cap open ios
npx cap open android

更多信息请参阅 电容器入门指南

🌐 See Capacitor's Getting Started guide for more.

框架集成

🌐 Framework Integrations

Ionic Core 也可以与支持自定义元素的其他框架和库一起使用,例如 Alpine.jsLitSvelte。然而,当将 Ionic Core 与这些库一起使用时,你将不会拥有与 Ionic 官方 Angular、React 和 Vue 框架集成紧密结合的内置表单和路由功能,而需要使用它们各自的路由和表单解决方案。

🌐 Ionic Core also works with other frameworks and libraries that support custom elements, such as Alpine.js, Lit, and Svelte. However, when using Ionic Core with these libraries, you won't have the built-in form and routing capabilities that are tightly coupled with Ionic's official Angular, React, and Vue framework integrations, and will need to use their respective routing and form solutions instead.

探索更多

🌐 Explore More

本指南涵盖了使用 Vite 创建 Ionic JavaScript 应用的基础知识、添加导航以及引入 Capacitor 以进行原生构建。要深入了解,请查看:

🌐 This guide covered the basics of creating an Ionic JavaScript app with Vite, adding navigation, and introducing Capacitor for native builds. To dive deeper, check out:

Vite 文档

学习用于 Ionic JavaScript 应用的高级 Vite 配置和优化技术。

JavaScript 文档

从 MDN Web 文档中了解有关 JavaScript 核心概念、工具和最佳实践的更多信息。

导航

了解如何在 Ionic JavaScript 应用中使用 Ionic Router 处理路由和导航。

组件

探索 Ionic 丰富的 UI 组件库,用于构建美观的应用。

主题化

了解如何使用 Ionic 强大的主题系统自定义应用的外观和感觉。

电容器文档

探索如何访问本地设备功能,并使用 Capacitor 将你的应用部署到 iOS、Android 和网络。