有一個(gè)需要使用TypeScript 重構(gòu)的項(xiàng)目垄潮,開始學(xué)習(xí)并研究TypeScript,并記錄在此過程中遇到的一些問題及解決方式
問題1: json|css|jpg等文件的導(dǎo)入
方式一 —寫聲明文件的方式
操作過程:
1闷盔、在項(xiàng)目根目錄下 ,與 src 文件夾同級牡整,建立name.d.ts 文件溺拱,用于聲明非js文件,也可以在一個(gè)Typings目錄下谣辞,新建x.d.ts文件
聲明文件的內(nèi)容
declare module "*.json"
declare module "*.png"
2泥从、引入文件資源,按照正常的方式引入即可
import * as name from '../package.json'
import { version } from '../package.json'
import name from '../package.json'
import { partname } from './package.json'
- 在tsconfig 文件的 配置信息中
"include": './*.d.ts' 引入 聲明文件
下面提到一些 對于導(dǎo)入非js 文件要引入的聲明文件的寫法:
- 官網(wǎng)推薦的方式
聲明文件:
declare module "*!text" {
const content: string;
export default content;
}
// Some do it the other way around.
declare module "json!*" {
const value: any;
export default value;
}
官網(wǎng)對于允許導(dǎo)入非js內(nèi)容的說明
Load a Json File with TypeScript
第二個(gè)鏈接文件需要翻墻沪摄,所以以下是其內(nèi)容
聲明文件和引入
// This will allow you to load `.json` files from disk
declare module "*.json"
{ const value: any;
export default value;
}
// This will allow you to load JSON from remote URL responses
declare module "json!*"
{ const value: any;
export default value;
}
然后需要在 使用的位置做出引入
import * as othername from './package.json'
import { version } from ''
- 方式二—require的方式
const Name = require('../../package.json');
還有注意的點(diǎn),
就是需要在 tsconfig.json 中的配置項(xiàng)中加入typings
{
"compilerOptions": {
"outDir": "./dist/",
"sourceMap": true,
"noImplicitAny": true,
"module": "commonjs",
"target": "es5",
"jsx": "react",
"experimentalDecorators": true 實(shí)驗(yàn)性的裝飾器語法使用報(bào)錯(cuò)
},
"include": [
"./src/**/*",
"./typings/**/*" 將聲明文件也要引入
]
}
如有錯(cuò)誤請批評指正