简体   繁体   English

使用webpack-dev-server读取webpack资产json

[英]Reading in webpack assets json with webpack-dev-server

Up until now, I've been building my isomorphic Node/Express/React app with webpack and serving up my bundle.js without a problem by including the following in my index html file: 到目前为止,我一直在使用webpack构建我的同构Node / Express / React应用程序并通过在我的索引html文件中包含以下内容来提供我的bundle.js而没有任何问题:

<script src='/bundle.js'></script>

However, for deploying to production I've found I need a cache-busting mechanism in place, so I reached for the webpack-manifest-plugin so I can add the unique build hash to the bundle.js file. 但是,为了部署到生产,我发现我需要一个缓存破坏机制,所以我找到了webpack-manifest-plugin,所以我可以将唯一的构建哈希添加到bundle.js文件中。

The webpack config with the plugin looks like: 带有插件的webpack配置如下所示:

webpack.config.js webpack.config.js

var ManifestPlugin = require('webpack-manifest-plugin');

var output = {
  path: path.join(__dirname, [ '/', config.get('buildDirectory') ].join('')),
  filename: "bundle.[hash].js"
};

which outputs a manifest.json file to the build directory that looks like: 它将manifest.json文件输出到构建目录,如下所示:

{
  "main.js": "bundle.af0dc43f681171467c82.js"
}

I was thinking I could then read in manifest.json with something like: 我以为我可以在manifest.json读取类似的内容:

var manifestPath = path.join(__dirname, [ '/', config.get('buildDirectory') ].join(''),'/manifest.json');
var manifest = require(manifestPath)

but I get 但我明白了

Error: Cannot find module 'C:\\Users\\banjer\\projects\\foo\\build\\manifest.json' 错误:找不到模块'C:\\ Users \\ banjer \\ projects \\ foo \\ build \\ manifest.json'

Is this because webpack-dev-server keeps the build directory in memory and not on disk (AFAIK)? 这是因为webpack-dev-server将构建目录保存在内存而不是磁盘上(AFAIK)? Whats the best method to read in this manifest.json and inject the bundle filename into my main index html file, eg?: 什么是读取此manifest.json的最佳方法,并将bundle文件名注入我的主索引html文件,例如?:

<script src='/bundle.af0dc43f681171467c82.js'></script>

The docs on these various asset plugins don't explain this step at all, but then again I think its less obvious because of webpack-dev-server...or something in my stack that I don't quite grasp yet. 关于这些各种资产插件的文档根本没有解释这个步骤,但是我再次认为它不太明显,因为webpack-dev-server ...或者我的堆栈中的某些东西我还没有完全掌握。

I went a simpler route and used version from package.json to append to bundle.js as a cache buster. 我使用了一个更简单的路由,并使用package.json中的version将bundle.js附加到缓存区。

webpack.config.js webpack.config.js

var output = {
  path: path.join(__dirname, [ '/', config.get('buildDirectory') ].join('')),
  filename: 'bundle.' + JSON.stringify(require('./package.json').version) + '.js'
};

module.exports = {
  output: output,
...
}

then I read in package.json in a similar manner from the entry script that generates my .ejs index file that has my script tags. 然后我以类似的方式从package脚本中读取,该脚本生成带有脚本标记的.ejs索引文件。

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

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