TypeScript
是 JavaScript
的超集,为其增加了类型声明验证,可以编译为 JavaScript
代码。这篇博文里我们将会学习如何集成 webpack
跟 TypeScript
。
项目地址:https://github.com/RiversCoder/webpack-test
ts
开发依赖cnpm install --D typescript ts-loader
tsconfig.json
文件{
"compilerOptions": {
"outDir": "./dist/",
"sourceMap": true,
"noImplicitAny": true,
"module": "es6",
"target": "es5",
"jsx": "react",
"allowJs": true
}
}
src
目录下新建index.ts
interface Person { name: string; age: number; }
let tom: Person = { name: 'Tom', age: 25 };
console.log(tom)
webpack.config.js
如下:const path = require('path');
const HTMLWebpackPlugin = require('html-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const webpack = require('webpack');
module.exports = {
entry: {
index: './src/index.ts'
},
devtool: 'inline-source-map',
module:{ // new add +
rules: [{
test: /\.tsx?$/,
use: 'ts-loader',
exclude: /node_modules/
}]
},
resolve: { // new add +
extensions: [ '.tsx', '.ts', '.js' ]
},
plugins: [
new CleanWebpackPlugin(),
new HTMLWebpackPlugin({
title: '全局引入lodash'
}),
new webpack.HashedModuleIdsPlugin(),
new webpack.ProvidePlugin({
lod: 'lodash'
})
],
output: {
filename: '[name].bundle.[chunkhash].js',
path: path.resolve(__dirname, 'dist')
}
};
D:\me\npm\test\webpack-test>npx webpack --config webpack.config.js
Hash: 7b8aa6a3b2de9f0f53d2
Version: webpack 4.34.0
Time: 25405ms
Built at: 2019-07-05 9:56:13 AM
Asset Size Chunks Chunk Names
index.bundle.334e8e718b2ebca8b3d9.js 7.23 KiB 0 [emitted] index
index.html 208 bytes [emitted]
Entrypoint index = index.bundle.334e8e718b2ebca8b3d9.js
[/7QA] ./src/index.ts 56 bytes {0} [built]
Child html-webpack-plugin for "index.html":
1 asset
Entrypoint undefined = index.html
[KQu2] (webpack)/buildin/global.js 472 bytes {0} [built]
[P7h0] (webpack)/buildin/module.js 497 bytes {0} [built]
+ 2 hidden modules
cnpm install --save-dev @types/jquery
(1)新建建立name.d.ts
文件,用于声明非js/ts
文件, 然后在tsconfig
中include
引入
xxx/xxx.d.ts
declare module "*.json"
declare module "*.png"
(2)配置tsconfig.json
文件信息
tsconfig.json
"include": 'xxx/*.d.ts' 引入 声明文件
(3)然后在ts
项目中就可以按照正常的方式引入即可
index.ts
import * as name from '../package.json'
import { partname } from './package.json'
(4)官网推荐的静态文件声明
xxx/xxx.d.ts
// 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;
}
declare module "*.svg" {
const content: any;
export default content;
}
webpack
配合typescript
开发,需要使用typescript
及ts-loader
,以及需要在module
中配置ts-loader
解析.ts
后缀的文件cnpm install @type/xxx
xxx.ts
文件中中声明该资源类型,然后在tsconfig.json
使用include
字段引入该xxx.ts
文件