TypeScript22(Rollup构建TS项目 webpack构建TS项目)

news2024/9/22 13:45:36

Rollup构建TS项目

安装依赖:

1.全局安装rollup: npm install rollup-g

2.安装TypeScript:   npm install typescript -D

3.安装TypeScript 转换器: npm install rollup-plugin-typescript2 -D

4.安装代码压缩插件: npm install rollup-plugin-terser -D

5. 安装rollupweb服务: npm install rollup-plugin-serve -D

6. 安装热更新: npm install rollup-plugin-livereload -D

7.引入外部依赖: npm install rollup-plugin-node-resolve -D

8.安装配置环境变量用来区分本地和生产:  npm install cross-env -D

9.替换环境变量给浏览器使用: npm install rollup-plugin-replace -D

配置package.json文件:

npm init -y

{
  "name": "rollupTs",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "dev": "cross-env NODE_ENV=development  rollup -c -w",
    "build":"cross-env NODE_ENV=produaction  rollup -c"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "cross-env": "^7.0.3",
    "rollup-plugin-livereload": "^2.0.5",
    "rollup-plugin-node-resolve": "^5.2.0",
    "rollup-plugin-replace": "^2.2.0",
    "rollup-plugin-serve": "^1.1.0",
    "rollup-plugin-terser": "^7.0.2",
    "rollup-plugin-typescript2": "^0.31.1",
    "typescript": "^4.5.5"
  }
}

配置rollup.config.js文件

console.log(process.env);
import ts from 'rollup-plugin-typescript2'
import path from 'path'
import serve from 'rollup-plugin-serve'
import livereload from 'rollup-plugin-livereload'
import { terser } from 'rollup-plugin-terser'
import resolve from 'rollup-plugin-node-resolve'
import repacle from 'rollup-plugin-replace'
 
const isDev = () => {
    return process.env.NODE_ENV === 'development'
}
export default {
    input: "./src/main.ts",
    output: {
        file: path.resolve(__dirname, './lib/index.js'),
        format: "umd",
        sourcemap: true
    },
 
    plugins: [
        ts(),
        terser({
            compress: {
                drop_console: !isDev()
            }
        }),
        repacle({
            'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV)
        }),
        resolve(['.js', '.ts']),
        isDev() && livereload(),
        isDev() && serve({
            open: true,
            openPage: "/public/index.html"
        })
    ]
}

配置tsconfig.json文件

{
  "compilerOptions": {
    /* Visit https://aka.ms/tsconfig.json to read more about this file */
 
    /* Projects */
    // "incremental": true,                              /* Enable incremental compilation */
    // "composite": true,                                /* Enable constraints that allow a TypeScript project to be used with project references. */
    // "tsBuildInfoFile": "./",                          /* Specify the folder for .tsbuildinfo incremental compilation files. */
    // "disableSourceOfProjectReferenceRedirect": true,  /* Disable preferring source files instead of declaration files when referencing composite projects */
    // "disableSolutionSearching": true,                 /* Opt a project out of multi-project reference checking when editing. */
    // "disableReferencedProjectLoad": true,             /* Reduce the number of projects loaded automatically by TypeScript. */
 
    /* Language and Environment */
    "target": "es5",                                  /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
    // "lib": [],                                        /* Specify a set of bundled library declaration files that describe the target runtime environment. */
    // "jsx": "preserve",                                /* Specify what JSX code is generated. */
    // "experimentalDecorators": true,                   /* Enable experimental support for TC39 stage 2 draft decorators. */
    // "emitDecoratorMetadata": true,                    /* Emit design-type metadata for decorated declarations in source files. */
    // "jsxFactory": "",                                 /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h' */
    // "jsxFragmentFactory": "",                         /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
    // "jsxImportSource": "",                            /* Specify module specifier used to import the JSX factory functions when using `jsx: react-jsx*`.` */
    // "reactNamespace": "",                             /* Specify the object invoked for `createElement`. This only applies when targeting `react` JSX emit. */
    // "noLib": true,                                    /* Disable including any library files, including the default lib.d.ts. */
    // "useDefineForClassFields": true,                  /* Emit ECMAScript-standard-compliant class fields. */
 
    /* Modules */
    "module": "ES2015",                                /* Specify what module code is generated. */
    // "rootDir": "./",                                  /* Specify the root folder within your source files. */
    // "moduleResolution": "node",                       /* Specify how TypeScript looks up a file from a given module specifier. */
    // "baseUrl": "./",                                  /* Specify the base directory to resolve non-relative module names. */
    // "paths": {},                                      /* Specify a set of entries that re-map imports to additional lookup locations. */
    // "rootDirs": [],                                   /* Allow multiple folders to be treated as one when resolving modules. */
    // "typeRoots": [],                                  /* Specify multiple folders that act like `./node_modules/@types`. */
    // "types": [],                                      /* Specify type package names to be included without being referenced in a source file. */
    // "allowUmdGlobalAccess": true,                     /* Allow accessing UMD globals from modules. */
    // "resolveJsonModule": true,                        /* Enable importing .json files */
    // "noResolve": true,                                /* Disallow `import`s, `require`s or `<reference>`s from expanding the number of files TypeScript should add to a project. */
 
    /* JavaScript Support */
    // "allowJs": true,                                  /* Allow JavaScript files to be a part of your program. Use the `checkJS` option to get errors from these files. */
    // "checkJs": true,                                  /* Enable error reporting in type-checked JavaScript files. */
    // "maxNodeModuleJsDepth": 1,                        /* Specify the maximum folder depth used for checking JavaScript files from `node_modules`. Only applicable with `allowJs`. */
 
    /* Emit */
    // "declaration": true,                              /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
    // "declarationMap": true,                           /* Create sourcemaps for d.ts files. */
    // "emitDeclarationOnly": true,                      /* Only output d.ts files and not JavaScript files. */
      "sourceMap": true,                                /* Create source map files for emitted JavaScript files. */
    // "outFile": "./",                                  /* Specify a file that bundles all outputs into one JavaScript file. If `declaration` is true, also designates a file that bundles all .d.ts output. */
    // "outDir": "./",                                   /* Specify an output folder for all emitted files. */
    // "removeComments": true,                           /* Disable emitting comments. */
    // "noEmit": true,                                   /* Disable emitting files from a compilation. */
    // "importHelpers": true,                            /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
    // "importsNotUsedAsValues": "remove",               /* Specify emit/checking behavior for imports that are only used for types */
    // "downlevelIteration": true,                       /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
    // "sourceRoot": "",                                 /* Specify the root path for debuggers to find the reference source code. */
    // "mapRoot": "",                                    /* Specify the location where debugger should locate map files instead of generated locations. */
    // "inlineSourceMap": true,                          /* Include sourcemap files inside the emitted JavaScript. */
    // "inlineSources": true,                            /* Include source code in the sourcemaps inside the emitted JavaScript. */
    // "emitBOM": true,                                  /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
    // "newLine": "crlf",                                /* Set the newline character for emitting files. */
    // "stripInternal": true,                            /* Disable emitting declarations that have `@internal` in their JSDoc comments. */
    // "noEmitHelpers": true,                            /* Disable generating custom helper functions like `__extends` in compiled output. */
    // "noEmitOnError": true,                            /* Disable emitting files if any type checking errors are reported. */
    // "preserveConstEnums": true,                       /* Disable erasing `const enum` declarations in generated code. */
    // "declarationDir": "./",                           /* Specify the output directory for generated declaration files. */
    // "preserveValueImports": true,                     /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */
 
    /* Interop Constraints */
    // "isolatedModules": true,                          /* Ensure that each file can be safely transpiled without relying on other imports. */
    // "allowSyntheticDefaultImports": true,             /* Allow 'import x from y' when a module doesn't have a default export. */
    "esModuleInterop": true,                             /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables `allowSyntheticDefaultImports` for type compatibility. */
    // "preserveSymlinks": true,                         /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
    "forceConsistentCasingInFileNames": true,            /* Ensure that casing is correct in imports. */
 
    /* Type Checking */
    "strict": true,                                      /* Enable all strict type-checking options. */
    // "noImplicitAny": true,                            /* Enable error reporting for expressions and declarations with an implied `any` type.. */
    // "strictNullChecks": true,                         /* When type checking, take into account `null` and `undefined`. */
    // "strictFunctionTypes": true,                      /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
    // "strictBindCallApply": true,                      /* Check that the arguments for `bind`, `call`, and `apply` methods match the original function. */
    // "strictPropertyInitialization": true,             /* Check for class properties that are declared but not set in the constructor. */
    // "noImplicitThis": true,                           /* Enable error reporting when `this` is given the type `any`. */
    // "useUnknownInCatchVariables": true,               /* Type catch clause variables as 'unknown' instead of 'any'. */
    // "alwaysStrict": true,                             /* Ensure 'use strict' is always emitted. */
    // "noUnusedLocals": true,                           /* Enable error reporting when a local variables aren't read. */
    // "noUnusedParameters": true,                       /* Raise an error when a function parameter isn't read */
    // "exactOptionalPropertyTypes": true,               /* Interpret optional property types as written, rather than adding 'undefined'. */
    // "noImplicitReturns": true,                        /* Enable error reporting for codepaths that do not explicitly return in a function. */
    // "noFallthroughCasesInSwitch": true,               /* Enable error reporting for fallthrough cases in switch statements. */
    // "noUncheckedIndexedAccess": true,                 /* Include 'undefined' in index signature results */
    // "noImplicitOverride": true,                       /* Ensure overriding members in derived classes are marked with an override modifier. */
    // "noPropertyAccessFromIndexSignature": true,       /* Enforces using indexed accessors for keys declared using an indexed type */
    // "allowUnusedLabels": true,                        /* Disable error reporting for unused labels. */
    // "allowUnreachableCode": true,                     /* Disable error reporting for unreachable code. */
 
    /* Completeness */
    // "skipDefaultLibCheck": true,                      /* Skip type checking .d.ts files that are included with TypeScript. */
    "skipLibCheck": true                                 /* Skip type checking all .d.ts files. */
  }
}

启动命令:npm run dev

打包命令:npm run build

webpack构建TS项目

安装依赖

安装webpack:   npm install webpack -D

webpack4以上需要: npm install  webpack-cli -D

编译TS:  npm install ts-loader -D

TS环境::npm install typescript -D

热更新服务::npm install  webpack-dev-server -D

HTML模板 :npm install html-webpack-plugin -D

配置文件

const path = require('path')
const htmlWebpackPlugin = require('html-webpack-plugin')
module.exports = {
    entry: "./src/index.ts",
    mode: "development",
    output: {
        path: path.resolve(__dirname, './dist'),
        filename: "index.js"
    },
    stats: "none",
    resolve: {
        extensions: ['.ts', '.js'],
        alias: {
            '@': path.resolve(__dirname, './src')
        }
    },
    module: {
        rules: [
            {
                test: /\.ts$/,
                use: "ts-loader"
            }
        ]
    },
    devServer: {
        port: 1988,
        proxy: {}
    },
    plugins: [
        new htmlWebpackPlugin({
            template: "./public/index.html"
        })
    ]
}

目录结构


 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/59927.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

项目:金融行业反欺诈模型

当今以互联网、移动终端等为代表的技术力量正深刻地影响着金融支付市场&#xff0c;信息化、网络化、无线终端等技术的应用&#xff0c;使金融机构特别是银行业的经营发生了天翻地覆的变化&#xff0c;传统的银行柜台和网点业务&#xff0c;正渐渐被电子化交易所替代&#xff0…

[附源码]计算机毕业设计基于SpringBoot的黄河文化科普网站

项目运行 环境配置&#xff1a; Jdk1.8 Tomcat7.0 Mysql HBuilderX&#xff08;Webstorm也行&#xff09; Eclispe&#xff08;IntelliJ IDEA,Eclispe,MyEclispe,Sts都支持&#xff09;。 项目技术&#xff1a; SSM mybatis Maven Vue 等等组成&#xff0c;B/S模式 M…

Golang开发变量声明命名惯例

《Go语言精进之路》第二、三章部分内容学习记录笔记。 1.基本原则 Golang开发中&#xff0c;可遵守简单且一致的命名原则&#xff0c;力求命名精简、易懂和一致。 package声明 Golang的package声明以小写形式的单个词进行命名&#xff1a; shopservice、utils、logs、tcc、l…

08_openstack之nova节点扩容

目录 一、环境准备 二、扩容节点配置 三、部署扩容节点 1、编辑answer.ini文件 2、执行安装 一、环境准备 部署openstack私有云环境&#xff1a;02_openstack私有云部署_桂安俊kylinOS的博客-CSDN博客 上述环境只部署了nova1节点&#xff0c;现将未部署的nova2节点作为扩…

1. Nginx 基本功能配置

Nginx 目录信息 图 为 windows 版本的。 进入Nginx的主目录我们可以看到这些文件夹 client_body_temp conf fastcgi_temp html logs proxy_temp sbin scgi_temp uwsgi_temp 其中这几个文件夹在刚安装后是没有的&#xff0c;主要用来存放运行过程中的临时文件 client_body_t…

20221104英语学习

今日单词&#xff1a; portable adj.轻便的&#xff0c;便携的&#xff1b;手提式的 beautiful adj.美丽的, 风和日丽的, 出色的 hunter n.猎人, 狩猎者, &#xff08;猎食其他动物的&#xff09;猎兽, 搜集某种东西的人 circle n.圆, 圈, 圆形, 圆圈 style n.样式, 风格,…

Unity 算法 之 点集中计算绘制 凸包 的简单整理

Unity 算法 之 点集中计算绘制 凸包 的简单整理 目录 Unity 算法 之 点集中计算绘制 凸包 的简单整理 一、简单介绍 二、Graham扫描法 第一种说明&#xff1a; 第二种说明&#xff1a; 三、代码&#xff08;第二种说明&#xff09; 四、参考文献 一、简单介绍 算法&…

工作上的三个境界:能做,能做好,能持续做好

某天&#xff0c;技术岗A员工抬杠管理岗B员工的工作&#xff1a;你的工作啊&#xff0c;实习生都能做&#xff0c;你的价值太小了........一顿DISS。 这样的场景&#xff0c;似曾相识否&#xff1f;这是职场中常见的一类人“杠精”的表现。 做技术的&#xff0c;往往认为管理…

MySQL8.0 OCP最新版1Z0-908认证考试题库整理-006

原题 Choose the best answer.You are having performance issues with MySQL instances. Those servers are monitored withMySQL Enterprise Monitor.Using Query Analyzer, where do you begin to look for problem queries?A) Sort the "Exec" column and check…

什么是物联网?如何保护物联网iot安全性

物联网iot:物联网&#xff08;IoT&#xff09;将生活中事物以网络进行连接&#xff0c;彼此交换信息。整个世界借由设备连接成一体。 对于消费者而言&#xff0c;这意味着您可以在大洋彼岸远程调节家中的恒温器。但是对企业而言&#xff0c;物联网不仅创造了连接客户和合作伙伴…

BBR 公平收敛

BBR 的公平收敛来自于两点&#xff1a; ProbeBW 状态加速比收敛&#xff1a;带宽越大&#xff0c;加速比越小。ProbeRTT 状态 RTT 收敛&#xff1a;inflight 越大&#xff0c;越容易让 inflight 小的测到 minrtt 而避免进入 ProbeRTT&#xff0c;inflight 越小&#xff0c;测量…

用Python代码自己写Python代码,竟如此简单

用Python代码自己写Python代码&#xff0c;竟如此简单 Python作为一门功能强大且使用灵活的编程语言&#xff0c;可以应用于各种领域&#xff0c;具有“无所不能”的特质。 Python甚至可以代替人&#xff0c;自己写Python代码。而且很简单&#xff0c;只需学会Python的基础知…

RabbitMQ学习笔记

目录 尚硅谷mq视频学习笔记 1.1. MQ 的相关概念 1.1.1. 什么是MQ 1.1.2. 为什么要用MQ 1.1.3. MQ 的分类 1.ActiveMQ 2.Kafka 3.RocketMQ 4.RabbitMQ 1.1.4. MQ 的选择 1.Kafka 2.RocketMQ 3.RabbitMQ 1.2. RabbitMQ 1.2.1. RabbitMQ 的概念 1.2.2. 四大核心概念…

7.7网络(二)

接上篇&#xff1a;7.7 网络&#xff08;一&#xff09;_龙赤子的博客-CSDN博客 目录 三 操作系统涉及的网络内容 1 网络栈 2 协议 3 应用 三 操作系统涉及的网络内容 1 网络栈 这里我们重点讨论操作系统里面的网络。这部分在整个网络架构中&#xff0c;属于端的技术。对于端来…

分布式锁-全面详解(学习总结---从入门到深化)

目录 分布式锁概述 为什么需要分布式锁 什么是分布式锁 分布式锁的特点 分布式锁问题_业务介绍 案列介绍 技术选型 创建表 创建订单表 创建商品表 创建订单商品关联表 分布式锁问题_创建SpringBoot项目 引入依赖 修改配置文件 编写主启动类 代码生成 编写创建订单接…

(附源码)node.js电商管理系统 毕业设计 251001

node.js电商管理系统 摘 要 随着科学技术的飞速发展&#xff0c;社会的方方面面、各行各业都在努力与现代的先进技术接轨&#xff0c;通过科技手段来提高自身的优势&#xff0c;电商管理系统当然也不能排除在外。电商管理系统 是以实际运用为开发背景&#xff0c;运用软件工程开…

【数据结构与算法】拓扑排序与关键路径

&#x1f525; 本文由 程序喵正在路上 原创&#xff0c;CSDN首发&#xff01; &#x1f496; 系列专栏&#xff1a;数据结构与算法 &#x1f320; 首发时间&#xff1a;2022年12月4日 &#x1f98b; 欢迎关注&#x1f5b1;点赞&#x1f44d;收藏&#x1f31f;留言&#x1f43e;…

【C++智能指针】智能指针的发展和循环引用的原理和解决

目录 1.RAIl&#xff08;智能指针的雏形&#xff09; 2.拷贝导致的问题以及智能指针发展历史 2.1拷贝的问题&#xff08;资源被析构两次&#xff09; 2.2auto_ptr(资源权转移&#xff0c;不建议使用) 2.3unique_ptr(防拷贝&#xff0c;在不需要拷贝的情况下使用) 2.4share…

【vue】vue-count-to(数字滚动)插件:

文章目录一、效果&#xff1a;二、使用&#xff1a;【1】安装插件【2】案例三、Options四、Functions一、效果&#xff1a; 二、使用&#xff1a; 官方文档&#xff1a; github地址——https://github.com/PanJiaChen/vue-countTo npm地址——https://www.npmjs.com/package/…

在本地PC运行 Stable Diffusion 2.0

Stable Diffusion 2.0在前几天已经发布了&#xff0c;新版本在上一个版本的基础上进行了许多改进。OpenCLIP中新的深度检测和更好的文本到图像模型是主要的改进之一。 有很多的文章介绍了Stable Diffusion 2.0的改进&#xff0c;所以我们就不多介绍了&#xff0c;这里我们将介…