Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
209 views
in Technique[技术] by (71.8m points)

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

My project is a JSON schema consisting of multiple JSON files:

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. I.e. a.json contains a ${version} (actual syntax is arbitrary, I don't have any preferences) placeholder in it's $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:

{
  "$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):

"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?

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. 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:

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...