新手使用webpack5搭建typescript项目

1,483 阅读2分钟

开发工具:vs-code

1、新建项目目录

本示例的开发目录为:books

2、初始化项目

npm init -y

完成后,本地会自动生成package.json文件,配置如下:

{
  "name": "books",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "build": "webpack",
    "start": "webpack serve"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}

项目启动: webpack serve

项目打包: webpack

注意:安装完依赖后再执行

3、初始化typescript

命令: tsc --init

完成后,本地会自动生成tsconfig.json文件。

使用时,可根据实际需求去掉相关注释,修改后,配置如下:

{
    "include":["./src/**/*"],
    "compilerOptions":{
        "module":"ES2015",
        "target":"ES2015",
        "strict":true,
        "outDir": "./dist",
        "noEmitOnError": true
    }
}

4、安装相关依赖

如: npm i webpack -D

webpack、 webpack-cli、 typescript、 ts-loader、 html-webpack-plugin:HTML插件、 webpack-dev-server:自动构建项目文件并自动刷新浏览器、 clean-webpack-plugin:自动删除以前打包的旧文件、 mini-css-extract-plugin:将 CSS 提取到单独文件、 copy-webpack-plugin:复制静态资源、 node-sass、 sass-loader、 babel-loader、 @babel/core、 @babel/preset-env、 style-loader、 postcss、 postcss-loader、 postcss-preset-env

安装完依赖后的package.json文件:

{
  "name": "books",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "build": "webpack",
    "start": "webpack serve"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@babel/core": "^7.14.8",
    "@babel/preset-env": "^7.14.8",
    "clean-webpack-plugin": "^4.0.0-alpha.0",
    "copy-webpack-plugin": "^9.0.1",
    "css-loader": "^6.2.0",
    "html-webpack-plugin": "^5.3.2",
    "mini-css-extract-plugin": "^2.1.0",
    "postcss": "^8.3.5",
    "postcss-loader": "^6.1.1",
    "postcss-preset-env": "^6.7.0",
    "sass-loader": "^12.1.0",
    "style-loader": "^3.2.1",
    "ts-loader": "^9.2.3",
    "typescript": "^4.3.5",
    "webpack": "^5.44.0",
    "webpack-cli": "^4.7.2",
    "webpack-dev-server": "^3.11.2"
  },
  "dependencies": {
    "babel-loader": "^8.2.2",
    "node-sass": "^6.0.1"
  }
}

注意:样式文件采用scss

5、创建入口文件

src:入口文件目录

index.ts:入口文件

index.html:首页

6、配置webpack

新建webpack.config.js文件

引入相关模块与插件:

const path = require('path');
const HTMLWebPlugin=require('html-webpack-plugin');
const {CleanWebpackPlugin}=require('clean-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');

具体配置如下:

module.exports = {
    entry: './src/index.ts',
    output: {
        path: path.resolve(__dirname, 'dist'),
        filename: '[name]_[hash:8].js',
        //配置打包环境,告诉webpack不使用箭头函数
        environment: {
            arrowFunction: false,
            const: false
        }
    },
    module: {
        rules: [
            {
                test: /\.ts$/,
                use: [
                    {
                        loader: 'babel-loader',
                        options: {
                            presets: ['@babel/preset-env']
                        }
                    },
                    'ts-loader'
                ],
                exclude: /node_modules/
            },
            {
                test: /\.scss$/,
                use: [
                    MiniCssExtractPlugin.loader,
                    'css-loader',
                    'sass-loader',
                    {
                        loader: "postcss-loader",
                        options: {
                            postcssOptions: {
                                plugins: [
                                    [
                                        "postcss-preset-env", {
                                            browsers: 'last 2 versions'
                                        }
                                    ]
                                ]
                            }
                        }
                    }                    
                ]
            }
        ]
    },
    resolve: {
        extensions: ['.ts', '.tsx', '.js']
    },
    mode: 'development',
    plugins: [
        new HTMLWebPlugin({
            template: "./src/index.html"
        }),
        new MiniCssExtractPlugin({
            filename: '[name]_[hash:8].css',
            chunkFilename: '[id].css'
        }),
        new CleanWebpackPlugin()
    ],
    devServer: {
        host: 'localhost',
        port: 8085,
        open: true
    }
}

成功启动项目界面:

image.png

7、样式

根据webpackconfig.js文件中的配置,可以直接引用.scss文件,在页面浏览时会自动生成一个样式文件,并对css3特性的部分自动追加-webkit前缀。

7.1 scss样式的使用:

样式目录:src\css

首页样式:index.scss @mixin bg(){ background: #efefef; } body{ @include bg(); }

index.ts文件引用index.scss文件:

import './css/index.scss'

7.2 css样式的使用:

配置同scss文件基本一致

{
    test:/\.css$/,
    use:[
        MiniCssExtractPlugin.loader,
        'css-loader',
        {
            loader: "postcss-loader",
            options: {
                postcssOptions: {
                    plugins: [
                        [
                            "postcss-preset-env", {
                                browsers: 'last 2 versions'
                            }
                        ]
                    ]
                }
            }
        }
    ]
}

注意事项: 当需要提取css样式时,use中不能加 style-loader