简体   繁体   English

Webpack 在构建时生成文件

[英]Webpack generate file on build

In my project at work we use Vue with VueI18n for localization.在我的工作项目中,我们使用 Vue 和 VueI18n 进行本地化。 We have one ref.js file which looks like this:我们有一个 ref.js 文件,如下所示:

export default {
  project: {
    lang: {
      test: {
        value: 'The test was a success',
        context: 'This string is a test string',
      },
    },
  },
},

This ref file is needed for the translation team and is our 'single source of truth'.翻译团队需要此参考文件,它是我们的“唯一真实来源”。 Now on build an en.js file is supposed to be generated.现在在构建时应该会生成一个 en.js 文件。 The en.js file would look like this: en.js 文件如下所示:

export default {
  project: {
    lang: {
      test: 'The test was a success',
    },
  },
},

Basically replacing the object under the test key with only its value.基本上只用它的值替换test key下的object。
Right now we have a file watcher running in the background which generates the en.js file every time the ref.js file changes.现在我们有一个在后台运行的文件观察器,它在每次 ref.js 文件更改时生成 en.js 文件。 What I would like is to integrate this en.js generation into the webpack build process.我想要的是将此 en.js 生成集成到 webpack 构建过程中。
Requirements are:要求是:

  • Generates en.js file on initial build在初始构建时生成 en.js 文件
  • Watches the ref.js file and generates en.js when ref.js file changes监视 ref.js 文件并在 ref.js 文件更改时生成 en.js

I tried writing a webpack plugin but didn't get very far.我尝试编写一个 webpack 插件,但没有走得太远。 I think the steps would be as follows:我认为步骤如下:

  • tap into beforeRun hook (generate file initilially)进入 beforeRun 钩子(最初生成文件)
  • tap into watchRun?/beforeCompile?进入 watchRun?/beforeCompile? -> check changed files and if ref.js is among them -> generate file -> 检查更改的文件,如果 ref.js 在其中 -> 生成文件

What I dont understand is where/how do I see which files have changed?我不明白在哪里/如何查看哪些文件已更改?

I would suggest you to create loader.我建议您创建加载程序。 You can define rule for your source file (ref.js) and your parser (loader) which will transform source into prefered form.您可以为源文件 (ref.js) 和解析器 (loader) 定义规则,将源文件转换为首选形式。

webpack.config.js webpack.config.js

module.exports = {
    (...)
    module: {
        rules: [
            {
                test: /ref\.js$/,
                loader: 'your-magic-loader',
            },
         (...)
        ]
    }
}

How to write a loader:如何编写加载器:
https://webpack.js.org/contribute/writing-a-loader/ https://webpack.js.org/contribute/writing-a-loader/

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

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