简体   繁体   English

Webpack 用于完全 static 项目(根本没有 JS / TS)

[英]Webpack for completely static project (no JS / TS at all)

My project is a JSON schema consisting of multiple JSON files:我的项目是一个 JSON 架构,由多个 JSON 文件组成:

src
├── a.json
├── b.json
└── c.json

All I want to do is to replace a version placeholder in this files with a version from package.json .我要做的就是用package.json中的版本替换此文件中的version占位符。 Ie a.json contains a ${version} (actual syntax is arbitrary, I don't have any preferences) placeholder in it's $id :a.json包含一个${version} (实际语法是任意的,我没有任何偏好)占位符$id

{
  "$schema": "http://json-schema.org/schema#",
  "$id": "https://foo.bar/${version}/a.json",
  "type": "object",
  …
}

And, assuming the version in package.json is 1.0.0 I want to process this JSON and get:并且,假设package.json中的version1.0.0我想处理这个 JSON 并得到:

{
  "$schema": "http://json-schema.org/schema#",
  "$id": "https://foo.bar/1.0.0/a.json",
  "type": "object",
  …
}

And that's it.就是这样。 It can be achieved by a script like this (in package.json ):它可以通过这样的脚本来实现(在package.json中):

"scripts": {
  "build": "rm -rf dist && mkdir dist && cp src/*.json dist/ && sed -i'' -e \"s/\\${version}/$npm_package_version/\" dist/*.json",
}

But how do I do it with Webpack?但是我该如何使用 Webpack 呢?

I know about copy and define plugins, but it seems that I need actual source in my project to be an entry point for Webpack.我知道复制和定义插件,但似乎我需要项目中的实际源代码作为 Webpack 的入口点。 A config like this:像这样的配置:

const CopyPlugin = require("copy-webpack-plugin");

module.exports = {
    mode: 'none',
    plugins: [
        new CopyPlugin({
            patterns: [
                {
                    from: "src/*.json",
                },
            ],
        }),
    ],
};

Copies files to dist (or wherever I want), but gives an error:将文件复制到dist (或我想要的任何地方),但给出错误:

ERROR in main
Module not found: Error: Can't resolve './src' in '/home/madhead/Projects/schema'

Another question here is how to copy and process those files (replace placeholders).这里的另一个问题是如何复制和处理这些文件(替换占位符)。

How do I only copy and process those JSONs with Webpack?如何仅使用 Webpack 复制和处理这些 JSON?

Try this one:试试这个:

new CopyWebpackPlugin([
    {from: 'src/*.json',
        to: '[name].[ext]',
        transform(content) {
            return content.toString().replace(/\${version}/g, '1.0.12');
        }
    }
])

And btw have no idea why you want to do this with webpack if you already know how to do it with basic script so you can just do it before or after webpack build.顺便说一句,如果您已经知道如何使用基本脚本执行此操作,那么您不知道为什么要使用 webpack 执行此操作,因此您可以在 webpack 构建之前或之后执行此操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM