使用Parcel打包TS代码,这可能是学习TS阶段相对简单的打包工具

613 阅读1分钟

大家好,我是一碗周,一个在舒适区垂死挣扎的前端,如果写的文章有幸可以得到你的青睐,万分有幸~

Parcel介绍

Parcel是一个和Webpack类似的一个打包工具,与之不同的是可以使用Parcel不需要任何的配置,可以帮助我们快速打包TypeScript代码,关于Parcel的使用,可以参考🚀 快速开始 (parceljs.org)

使用Parcel打包TS代码

  1. 初始化项目

    npm init -y
    tsc --init 
    
  2. 将Parcel下载的项目中,示例代码如下:

    npm i -D parcel-bundler
    
  3. 配置tsconfig.json文件,配置rootDir选项和outDir选项,配置如下:

    {
        "compilerOptions": {
            "target": "es5", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019' or 'ESNEXT'. */
            "module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */
            // 打包后目录
            "outDir": "./dist", /* Redirect output structure to the directory. */
            // 打包的目录
            "rootDir": "./src", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
            "strict": true, /* Enable all strict type-checking options. */
            "esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
        }
    }
    
  4. 创建一个.ts文件和.html文件,并写入如下内

    // page.ts
    const myName: string = '一碗周'
    console.log(myName)
    
    <!-- index.html -->
    <!DOCTYPE html>
    <html lang="en">
        <head>
            <meta charset="UTF-8" />
            <meta http-equiv="X-UA-Compatible" content="IE=edge" />
            <meta name="viewport" content="width=device-width, initial-scale=1.0" />
            <title>Document</title>
            <script src="./page.ts"></script>
        </head>
        <body></body>
    </html>
    
    
  5. 配置package.json文件中的script选项,配置如下:

    "scripts": {
        "test": "parcel ./src/index.html"
    }
    
  6. 目前为止我们的环境就配置好了,在命令行中输入npm run test即可编译我们的代码,并创建了一个开发服务器。

    npm run test
    

然后在浏览器中打开 http://localhost:1234/,即可看见我们编写的代码。