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"
}

最新文章

  1. Linux上oracle精简版客户端快速部署
  2. activemq jmsTemplate 发送消息速度太慢
  3. 【HDU 5833】Zhu and 772002(异或方程组高斯消元)
  4. python检测文件的MD5值
  5. BZOJ4517: [Sdoi2016]排列计数
  6. Kali Linux Web 渗透测试视频教程—第十一课-扫描、sql注入、上传绕过
  7. Android安全之WebViewUXSS漏洞
  8. MES取所有部门的函数实例
  9. Jenkins 安装与配置
  10. js提交前弹出提示框
  11. win7 64位的apache2.4.9+php5.5+mysql5.6的安装
  12. linux小白成长之路1————通过Parallels安装CentOS虚拟机
  13. [知识梳理]课本1&amp;2.1-2.5
  14. HTML学习笔记 day two
  15. 【python深入】dict和list实现排序:sorted()和lambda的使用
  16. Ball CodeForces - 12D (线段树)
  17. scala中隐式转换之总结
  18. propTypes
  19. [转]Filter 过滤器
  20. r语言 load Rdata 获取表名 并直接转为数据表

热门文章

  1. PyTorch专栏(一)
  2. PHP7内核(五):系统分析生命周期
  3. Codeforces题解集 1.0
  4. 图解JVM内存区域划分
  5. 面向对象编程基础(java)
  6. 空间复杂度(Space Complexity)
  7. Django之auth用户认证
  8. B 【ZJOI2007】时态同步
  9. @Configuration和@Bean 配置类注入
  10. vs code 关闭保存自动格式化 formatonsave - [vscode] - [html]