Initialize the project

create a folder project

Now we’ll turn this folder into an npm package.

npm init -y

This creates a package.json file with default values.

Install our dependencies

First ensure Webpack is installed.

npm install --save-dev webpack webpack-cli

Webpack is a tool that will bundle your code and optionally all of its dependencies into a single .js file.

Let’s now add React and React-DOM, along with their declaration files, as dependencies to your package.json file:

npm install --save react react-dom
npm install --save-dev @types/react @types/react-dom

That @types/ prefix means that we also want to get the declaration files for React and React-DOM. Usually when you import a path like "react", it will look inside of the react package itself; however, not all packages include declaration files, so TypeScript also looks in the @types/react package as well. You’ll see that we won’t even have to think about this later on.

Next, we’ll add development-time dependencies on the ts-loader and source-map-loader.

npm install --save-dev typescript ts-loader source-map-loader

Both of these dependencies will let TypeScript and webpack play well together. ts-loader helps Webpack compile your TypeScript code using the TypeScript’s standard configuration file named tsconfig.json. source-map-loader uses any sourcemap outputs from TypeScript to inform webpack when generating its own sourcemaps. This will allow you to debug your final output file as if you were debugging your original TypeScript source code.

Please note that ts-loader is not the only loader for typescript. You could instead use awesome-typescript-loader.

Read about the differences between them:

https://github.com/s-panferov/awesome-typescript-loader#differences-between-ts-loader

Notice that we installed TypeScript as a development dependency. We could also have linked TypeScript to a global copy with npm link typescript, but this is a less common scenario.

Add a TypeScript configuration file #

You’ll want to bring your TypeScript files together - both the code you’ll be writing as well as any necessary declaration files.

To do this, you’ll need to create a tsconfig.json which contains a list of your input files as well as all your compilation settings. Simply create a new file in your project root named tsconfig.json and fill it with the following contents:

{
"compilerOptions": {
"outDir": "./dist/",
"sourceMap": true,
"noImplicitAny": true,
"module": "commonjs",
"target": "es6",
"jsx": "react"
}
}

You can learn more about tsconfig.json files:

http://www.typescriptlang.org/docs/handbook/tsconfig-json.html

Write some code

Let’s write our first TypeScript file using React. First, create a file named Hello.tsx in src/components and write the following:

import * as React from "react";

export interface HelloProps { compiler: string; framework: string; }

export const Hello = (props: HelloProps) => <h1>Hello from {props.compiler} and {props.framework}!</h1>;

Note that while this example uses function components, we could also make our example a little classier as well.

import * as React from "react";

export interface HelloProps { compiler: string; framework: string; }

// 'HelloProps' describes the shape of props.
// State is never set so we use the '{}' type.
export class Hello extends React.Component<HelloProps, {}> {
render() {
return <h1>Hello from {this.props.compiler} and {this.props.framework}!</h1>;
}
}

Next, let’s create an index.tsx in src with the following source:

import * as React from "react";
import * as ReactDOM from "react-dom"; import { Hello } from "./components/Hello"; ReactDOM.render(
<Hello compiler="TypeScript" framework="React" />,
document.getElementById("example")
);

We just imported our Hello component into index.tsx. Notice that unlike with "react" or "react-dom", we used a relative path to Hello.tsx - this is important. If we hadn’t, TypeScript would’ve instead tried looking in our node_modules folder.

We’ll also need a page to display our Hello component. Create a file at the root of proj named index.htmlwith the following contents:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Hello React!</title>
</head>
<body>
<div id="example"></div> <!-- Dependencies -->
<script src="./node_modules/react/umd/react.development.js"></script>
<script src="./node_modules/react-dom/umd/react-dom.development.js"></script> <!-- Main -->
<script src="./dist/main.js"></script>
</body>
</html>

Notice that we’re including files from within node_modules. React and React-DOM’s npm packages include standalone .js files that you can include in a web page, and we’re referencing them directly to get things moving faster. Feel free to copy these files to another directory, or alternatively, host them on a content delivery network (CDN). Facebook makes CDN-hosted versions of React available, and you can read more about that here.

https://reactjs.org/docs/getting-started.html#development-vs.-production-builds


Create a webpack configuration file

Create a webpack.config.js file at the root of the project directory.

module.exports = {
mode: "production", // Enable sourcemaps for debugging webpack's output.
devtool: "source-map", resolve: {
// Add '.ts' and '.tsx' as resolvable extensions.
extensions: [".ts", ".tsx"]
}, module: {
rules: [
{
test: /\.ts(x?)$/,
exclude: /node_modules/,
use: [
{
loader: "ts-loader"
}
]
},
// All output '.js' files will have any sourcemaps re-processed by 'source-map-loader'.
{
enforce: "pre",
test: /\.js$/,
loader: "source-map-loader"
}
]
}, // When importing a module whose path matches one of the following, just
// assume a corresponding global variable exists and use that instead.
// This is important because it allows us to avoid bundling all of our
// dependencies, which allows browsers to cache those libraries between builds.
externals: {
"react": "React",
"react-dom": "ReactDOM"
}
};

Putting it all together

npx webpack

引入html-webpack-plugin 实现html模版自动生成

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin'); module.exports = {
entry: "./src/index.tsx",
output: {
path: path.join(__dirname, '/dist'),
filename: 'bundle.js'
},
devtool: "source-map",
resolve: {
// Add '.ts' and '.tsx' as resolvable extensions.
extensions: [".ts", ".tsx", ".js", ".json"]
},
module: {
rules: [
// All files with a '.ts' or '.tsx' extension will be handled by 'awesome-typescript-loader’.
{ test: /\.tsx?$/, loader: "awesome-typescript-loader" },
// All output '.js' files will have any sourcemaps re-processed by 'source-map-loader'.
{ enforce: "pre", test: /\.js$/, loader: "source-map-loader" }
]
},
plugins: [
new HtmlWebpackPlugin({
template: './index.html'
})
],
// 用来替换全局变量
// externals: {
// react: "React",
// "react-dom": "ReactDOM"
// }
};

npm i webpack-dev-server -D

更新package.json

"scripts": {
"start": "webpack-dev-server --mode development --open --hot",
"build": "webpack --mode production"
}

react: typescript project initialize的更多相关文章

  1. react typescript jest config (一)

    1. initialize project create a folder project Now we'll turn this folder into an npm package. npm in ...

  2. react + typescript 学习

    react,前端三大框架之一,也是非常受开发者追捧的一门技术.而 typescript 是 javascript 的超集,主要特点是对 类型 的检查.二者的结合必然是趋势,不,已经是趋势了.react ...

  3. React + Typescript领域初学者的常见问题和技巧

    React + Typescript领域初学者的常见问题和技巧 创建一个联合类型的常量 Key const NAME = { HOGE: "hoge", FUGA: "f ...

  4. 【每天学一点-04】使用脚手架搭建 React+TypeScript+umi.js+Antd 项目

    一.使用脚手架搭建项目框架 1.首先使用脚手架搭建React项目(React+TypeScript+Umi.js) 在控制台输入命令:yarn create @umijs/umi-app 2.引入An ...

  5. 前端自动化测试 —— TDD环境配置(React+TypeScript)

    欢迎讨论与指导:) 前言 TDD -- Test-Drive Development是测试驱动开发的意思,是敏捷开发中的一项核心实践和技术,也是一种测试方法论.TDD的原理是在开发功能代码之前,先编写 ...

  6. React + TypeScript:元素引用的传递

    React 中需要操作元素时,可通过 findDOMNode() 或通过 createRef() 创建对元素的引用来实现.前者官方不推荐,所以这里讨论后者及其与 TypeScript 结合时如何工作. ...

  7. react+typescript报错集锦<持续更新>

    typescript报错集锦 错误:Import sources within a group must be alphabetized.tslint(ordered-imports) 原因:impo ...

  8. React & TypeScript

    之前看了一下 TypeScript 的知识,但是一直没有上手,最近开始结合 React 和 TypeScript 一起尝试了一下,感受还是很好的,所以写一下笔记. 环境配置没有参考其他东西,就是看了下 ...

  9. [TypeScript] Dynamically initialize class properties using TypeScript decorators

    Decorators are a powerful feature of TypeScript that allow for efficient and readable abstractions w ...

随机推荐

  1. AJAX完全解读

    本文讲AJAX相关的知识全部讲解了一遍.要想入门,选择这篇文章完全够用 本文的知识图谱: AJAX的用处: ​ 在没有AJAX之前,每次从服务端获取数据都要刷新页面(也就是同步请求),这十分的麻烦.比 ...

  2. Java程序员必读的9本书

    本文列出的9本书在Java程序员界都是被认为很棒的书.当一个程序员开始初学Java时,他的第一个问题应该是如何选择一本书来作为指导学习Java.这个问题也就表明,相对于其他的教程和博客,Java书籍还 ...

  3. SpringCloud入门(九): Zuul 上传&回退&异常处理&跨域

    Zuul的上传 1.构建一个上传类 import org.springframework.web.bind.annotation.PostMapping; import org.springframe ...

  4. Activiti网关--包含网关

    1.什么是包含网关 包含网关可以看做是排他网关和并行网关的结合体:和排他网关一样,你可以在外出顺序流上定义条件,包含网关会解析它们:但是主要的区别是包含网关可以选择多于一条顺序流,这和并行网关一样,包 ...

  5. jQuery和Vue的技术优劣对比

    1.精力集中. Jq偏重于对dom的操作,由它的函数就很容易看出来,$().parent().find().我们用jq的时候经常要去考虑怎么去渲染数据,怎么从视图中取到数据,操作数据前必须对dom节点 ...

  6. Python语言上机题实现方法(持续更新...)

    Python语言上机题实现方法(持续更新...) 1.[字符串循环左移]给定一个字符串S,要求把S的前k个字符移动到S的尾部,如把字符串"abcdef"前面的2个字符'a'.'b' ...

  7. Hadoop(四):HDFS读数据的基本流程

    HDFS读数据的流程 shell发送下载请求 NameNode检测文件系统,查找a的元数据(block和block所在的位置信息) 返回元数据给shell,返回的元数据会排序,排序规则: 拓扑距离近排 ...

  8. 关于Tkinter的介绍

    Introduction to Tkinter 原英文教程地址zetcode.com In this part of the Tkinter tutorial, we introduce the Tk ...

  9. 家庭记账本app进度之复选框以及相应滚动条的应用

    这次主要是对于android中复选框的相应的操作.以及其中可能应用到的滚动条的相关应用.每一个复选框按钮都要有一个checkBox与之相对应. 推荐使用XML配置,基本语法如下:<CheckBo ...

  10. flask-migrate的基本使用

    Flask-migrate 在实际开发环境中,经常会发生数据库修改的行为.一般我们修改数据库不会手动的去修改,而是去修改orm对应的模型, 然后再把模型映射到数据库中.这时候如果有一个工具能专门做这种 ...