ts项目初始化

1. 全局安装

npm i typescript -g
npm i tslint -g

2. 项目初始化

npm init     // 生成package.json
tsc --init    // 生成tsconfig.json

tsconfig.json文件内容(对于其中每一项的含义,后面补充)

 3.项目中安装typescript, webpack, webpack-cli, webpack-dev-server

npm i typescript 
npm i webpack webpack-cli webpack-dev-server -D

4. 手动添加文件夹,项目目录结构如下:

 

 

 5. 在package.json中增加scripts

 "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "cross-env NODE_ENV=development webpack-dev-server --config ./build/webpack.config.js",
    "build": "cross-env NODE_ENV=production webpack --config ./build/webpack.config.js"
  },

对于开发环境,添加start:前半段使用cross-env传递 NODE_ENV=development  变量,后半段以  ./build/webpack.config.js 中的配置运行webpack-dev-server。

对于生产环境,添加build: 注意后半段用的是webpack而非webpack-dev-server, 前半段通过cross-env传递的变量NODE_ENV值为production

cross-env需要安装

npm i cross-env -D

6. webpack.config.js配置

const path = require('path');
const HTMLWebpackPlugin = require('html-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');

module.exports = {
    entry: path.join(__dirname, "../src/index.ts"),
    output: {
        path: path.join(__dirname, "../dist"),
        filename: "main.js"
    },
    resolve: {
        extensions: ['.js', '.ts', '.tsx']
    },
    module: {
        rules: [{
            test: /\.tsx?$/,
            use: 'ts-loader',
            exclude: /node_modules/
        }]
    },
    devtool: process.env.NODE_END === 'production' ? false : 'inline-source-map',
    devServer: {
        // contentBase: path.join(__dirname, '../dist'),
        stats: 'errors-only',
        compress: false,
        host: 'localhost',
        port: 8099
    },
    plugins: [
        new CleanWebpackPlugin({
            CleanOnceBeforeBuildPatterns: [path.join(__dirname, './dist')]
        }),
        new HTMLWebpackPlugin({
            template: './src/template/index.html'
        })
    ]
}

 

posted @ 2020-06-02 17:11  cecelia  阅读(1866)  评论(0编辑  收藏  举报