【问题标题】:How to serve a json file with parcel without bundling it?如何在不捆绑的情况下使用包裹提供 json 文件?
【发布时间】:2020-11-16 00:52:44
【问题描述】:

我正在用包裹和打字稿制作一个项目。它工作得很好,但是对于我正在使用的一个库,我需要在一个固定目录中托管一堆 .json 文件:

文件如下:

index.html
index.ts
tiles/
 | file.json
 | file0.json
 | subdirectory with *.json

package.json 中,我将它们包括为parcel *.html tiles/*(用于start)和parcel build index.html tiles/*,但这会导致将json 文件构建到一些.js 文件中。但是,我需要它们按原样提供。

关于如何告诉包裹捆绑它们的任何提示?

【问题讨论】:

标签: json assets parceljs


【解决方案1】:

您可以覆盖 .parcelrc 文件中用于 JSON 文件的转换器插件。默认使用@parcel/transformer-json,但您可以使用@parcel/transformer-raw 将JSON文件视为资产。

.parcelrc

{
  "extends": "@parcel/config-default",
  "transformers": {
    "*.json": ["@parcel/transformer-raw"]
  }
}

【讨论】:

    【解决方案2】:

    如果您使用 Parcel 2,则可以执行以下操作:

    import jsonUrl from 'url:./data.json'
    
    // Fetch the file asynchronously from the URL
    fetch(jsonUrl)
      .then(response => response.json())
      .then(json => ...)
      ... etc. ...
    

    【讨论】:

      【解决方案3】:

      有一个 npm 包可以做到这一点:https://www.npmjs.com/package/parcel-plugin-static-files-copy

      npm install -D parcel-plugin-static-files-copy 安装(仅用于开发)

      然后,在package.json 中,添加:

      "staticFiles": {
          "staticPath": [
            {
              "staticPath": "tiles", -- copy all files from this directory at the root from your project...
              "staticOutDir": "tiles/" -- ... to this directory in dist/, so it becomes dist/tiles/<files>
            }
          ]
        }
      
      ``` 
      
      Note that you have to define a `staticPath` in the list `staticPath`, this is a bit confusing at first.
      

      【讨论】:

      • 是的,这个方法有效,我在最近的一个项目中做过同样的事情。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-13
      • 1970-01-01
      • 2010-10-10
      • 1970-01-01
      • 2018-06-16
      相关资源
      最近更新 更多