自学内容网 自学内容网

webpack + ts 搭建 web 应用

初始化

npm init -y

一、 依赖下载

typescript相关:

ts-loader: ts文件加载器

npm i typescript ts-loader -D

webpack相关

webpack-cli: 命令行工具
webpack-dev-server:webpack开发服务器
webpack-merge : webpack配置合并
clean-webpack-plugin: webpack中的清除插件,每次构建都会先清除目录
html-webpack-plugin: webpack中html插件,用来自动创建html文件

npm i webpack webpack-cli webpack-dev-server webpack-merge clean-webpack-plugin html-webpack-plugin -D

babel相关

babel-loader: babel的加载器
core-js: 用来使老版本的浏览器支持新版ES语法

npm i babel babel-loader core-js

二、创建index.ts

src/index.ts

console.log("hello Ts");

三、配置tsconfig.json

{
  "compilerOptions": {
    "target": "ES2015",
    "module": "ES2015",
    "strict": true,
  }
}

四、配置webpack开发、生产环境

build/

// webpack.base.config.js
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");

module.exports = {
  entry: "./src/index.ts",
  output: {
    path: path.resolve(__dirname, "dist"),
    filename: "bundle.js"
  },
  resolve: {
    extensions: [".js", ".ts"],
  },
  module: {
    rules: [
      {
        test: /.ts$/,
        use: [
          {
            loader: "babel-loader",
            // 设置babel
            options: {
              // 设置预定义的环境
              presets: [
                [
                  // 指定环境的插件
                  "@babel/preset-env",
                  // 配置信息
                  {
                    // 要兼容的目标浏览器
                    targets: {
                      chrome: "58",
                      ie: "11",
                    },
                    // 指定corejs的版本
                    corejs: "3",
                    // 使用corejs的方式 "usage" 表示按需加载
                    useBuiltIns: "usage",
                  },
                ],
              ],
            },
          },
          {
            loader: "ts-loader",
          },
        ],
        exclude: /node_modules/,
      },
    ]
  },
  plugins: [
    new HtmlWebpackPlugin(
      {
        template:"index.html"//使用基本模版,可在根目录创建
      }
    ),
  ],
};
//webpack.base.config.js
const { merge } = require("webpack-merge");
const baseConfig = require("./webpack.base.config");
const devConfig = require("./webpack.dev.config");
const proConfig = require("./webpack.pro.config");

module.exports = (env, argv) => {
  let config = argv.mode === "development" ? devConfig : proConfig;
  return merge(baseConfig, config);
};
//webpack.dev.config.js
module.exports = {
  devtool: "inline-source-map",
};
// webpack.pro.config.js
const { CleanWebpackPlugin } = require("clean-webpack-plugin");

module.exports = {
  plugins: [new CleanWebpackPlugin()],
};

五、配置package.json命令

  "scripts": {
    "start": "webpack-dev-server --mode=development --config ./build/webpack.config.js",
    "build": "webpack --mode=production --config ./build/webpack.config.js"
  },

原文地址:https://blog.csdn.net/sfumato/article/details/137789454

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!