webpack编译typescript

1、安装nodejs

2、安装cnpm

npm install -g cnpm --registry=https://registry.npm.taobao.org

3、安装全局typescript

cnpm install -g typescript

4、使用cnpm初始化编译环境

npm init -y #初始化package.json
tsc --init #初始化tsconfig.json

5、项目安装typescript和loader

cnpm install --save-dev typescript ts-loader

6、安装webpack和相关依赖

npm intall webpack webpack-cli webpack-dev-server --save-dev

7、新建webpack.config.js

const path = require(‘path‘); //node模块
module.exports = {
    entry: {
        demo: path.join(__dirname, ‘./src/demo.ts‘)
    },
    output: {
        filename: ‘[name].bundle.js‘,
        path: path.join(__dirname, ‘./dist‘)
    },
    module: { 
        //配置一个rules(规则),rules是一个数组,里面包含一条一条的规则
        rules: [{
            test: /.tsx?$/,
            use: "ts-loader",
            exclude: /node_modules/
        }]
    }
}

8、在package.json设置启动脚本

"scripts": {
    "webpack": "webpack --mode=production --watch"
  },

9、运行编译

npm run webpack

相关推荐