ionic 创建指定版本项目

使用ionic start 创建项目的版本主要与ionic-cli有关,所以即使你安装ionic@3.9.2 和低版本的node,创建出来的依然是新版本的项目文件。

使用 最新ionic-cli 创建ionic3项目

--type=<type>
Description
Type of project to start (e.g. angular, react, ionic-angular, ionic1)

//创建ionic3项目
ionic start tabTest --type=ionic-angular

使用相对路径缩短 import 路径

在写Vue的时候默认会配置WebPack,’@‘即代表src目录,所以引用的时候就可以方便的相对src导入而不用不断的 ../ 了。

//import { Home } from '../../../components/home'

import { Home } from '@/components/home'

而用ionic-cli创建的项目默认并没有这样的配置,所以需要自己动手丰衣足食。

新建项目

 ionic start myApp blank  --type=ionic-angular

打开项目的‘app.component.ts’ 文件,可以看到默认有个Home Page的引入:
我们的目标就是将其改成 @xxx形式的相对路径引入。

import { HomePage } from '../pages/home/home';
//import { HomePage } from '@/pages/home/home';

配置 tsconfig.json

根目录打开名为 tsconfig.json的文件,内容如下:

{
  "compilerOptions": {
    "baseUrl": "./src",
    "paths": {
      "@app/*": [
        "app/*"
      ],
      "@pages/*": [
        "pages/*"
      ],
      "@services/*": [
        "services/*"
      ]},
    "allowSyntheticDefaultImports": true,
    "declaration": false,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "lib": [
      "dom",
      "es2015"
    ],
    "module": "es2015",
    "moduleResolution": "node",
    "sourceMap": true,
    "target": "es5"
  },
  "include": [
    "src/**/*.ts"
  ],
  "exclude": [
    "node_modules",
    "src/**/*.spec.ts",
    "src/**/__tests__/*.ts"
  ],
  "compileOnSave": false,
  "atom": {
    "rewriteTsconfig": false
  }
}

在 compilerOptions下添加:

"baseUrl": "./src", //This make VS code aware of alias imports
"paths": {
   "@app/*": ["app/*"], // Created aliases for different folders
   "@pages/*": ["pages/*"],
   "@services/*": ["services/*"]
}

配置 webpack.config.js

在项目根目录下创建 webpack.config.js , 并填入以下配置:

const path = require('path');
const useDefaultConfig = require('@ionic/app-scripts/config/webpack.config.js');

const env = process.env.IONIC_ENV;

useDefaultConfig[env].resolve.alias = {
    "@app": path.resolve('./src/app/'),
    "@pages": path.resolve('./src/pages/'),
    "@services": path.resolve('./src/services/'),

};

module.exports = function () {
    return useDefaultConfig;
};

配置 package.json

在根目录下的 package.json 添加配置,使我们的 webpack 配置起作用:

"config": {
    "ionic_source_map_type": "source-map",
    "ionic_webpack": "./webpack.config.js"
  },

验证

现在引用HomePage,将../相对路径改为@page

//import { HomePage } from '../pages/home/home';
import { HomePage } from '@/pages/home/home';

如果使用的VS Code提示无法找到引入文件,尝试ctrl+shift+p reload 项目。

评论

此博客中的热门博文

1. Angular 错误:ExpressionChangedAfterItHasBeenCheckedError