問題描述
我正在使用 Webpack 2 和 Electron 在 Mac 上構建 nodejs 應用程序.
在我的根目錄中的項目中,我有目錄數據",我將配置存儲在 json 中,例如 data/configurations/files.json(實際上有不同的文件具有動態名稱)
雖然當我調用 webpackaing 后: fs.readdirSync(remote.app.getAppPath());
以獲取根目錄中的文件,但我只得到這些打包: [ "default_app.js"、"icon.png"、"index.html"、"main.js"、"package.json"、"renderer.js"]
path.join(remote.app.getAppPath(), 'data/tests/groups.json');
使用 FS ReadSync 調用會導致問題 Error: ENOENT, data/在/Users/myuser/myproject/node_modules/electron/dist/Electron.? app/Contents/Resourc? es/default_app.asar
中找不到 tests/groups.json.所以似乎整個數據文件夾都沒有被 webpacker 拾取.
Webpack 配置正在使用 json-loader
并且我沒有找到任何文檔提到有關包含特定文件或 json 的任何特殊內容.或者我是否必須在我的代碼中以不同的方式引用 json 文件,因為它們可能打包在 main.js 下.
Electron/Webpack 管理 JSON 配置文件的最佳實踐是什么?在 webpacking 項目時我做錯了什么嗎?
我的項目基于 https://github.com/SimulatedGREG/electron-vue使用 webpack/electron/vue
Webpack 的誤解
首先要了解的一點是,webpack
不會捆綁通過 fs
或其他要求文件路徑的模塊所需的文件.這些類型的資產通常被標記為靜態資產,因為它們沒有以任何方式捆綁在一起.webpack
只會捆綁 require
d 或 import
ed (ES6) 的文件.此外,根據您的 webpack
配置,您的項目根目錄可能并不總是與生產構建中的輸出相匹配.
根據electron-vue文檔的Project Structure/File Tree,你會發現只有webpack
包和static/
目錄在生產版本中可用.electron-vue 還有一個方便的 __static
全局變量,可以在開發和生產環境中提供該 static/
文件夾的路徑.您可以使用此變量,類似于使用 __dirname
和 path.join
來訪問您的 JSON 文件或任何文件.
靜態資產的解決方案
electron-vue 樣板的當前版本似乎已經為您解決了這個問題,但我將描述如何使用 webpack
進行設置,因為它不僅可以應用于 JSON 文件,還可以應用于任何 webpack
+ electron
設置.以下解決方案假設您的 webpack
構建輸出到一個單獨的文件夾,在這種情況下我們將使用 dist/
,假設您的 webpack
配置是位于項目的根目錄中,并假定在開發過程中將 process.env.NODE_ENV
設置為 development
.
static/
目錄
在開發過程中,我們需要一個地方來存儲我們的靜態資產,所以讓我們將它們放在一個名為 static/
的目錄中.在這里,我們可以放置我們知道需要使用 fs
或其他需要文件完整路徑的模塊讀取的文件,例如 JSON.
現在我們需要使 static/
資產目錄在生產構建中可用.
但是 webpack
根本不處理這個文件夾,我們該怎么辦?
讓我們使用簡單的copy-webpack-plugin
.在我們的 webpack
配置文件中,我們可以在構建 for production 時添加這個插件,并將其配置為將 static/
文件夾復制到我們的 dist/
文件夾.
新的 CopyWebpackPlugin([{來自:path.join(__dirname, '/static'),to: path.join(__dirname, '/dist/static'),忽略: ['.*']}])
<塊引用>
好的,資產已投入生產,但如何在開發和生產中獲取此文件夾的路徑?
創建一個全局 __static
變量
<塊引用>使這個 __static
變量有什么意義?
在
webpack
+electron
設置中使用__dirname
不可靠.在開發過程中,__dirname
可以引用存在于您的src/
文件中的目錄.在生產中,由于webpack
將我們的src/
文件捆綁到一個腳本中,因此您形成的到達static/
的路徑不再存在.此外,您放在src/
中的那些不是require
d 或import
ed 的文件永遠不會進入您的生產版本.在處理開發和生產的項目結構差異時,在開發過程中嘗試獲取到
static/
的路徑將非常煩人,必須始終檢查您的process.env.NODE_ENV
.
讓我們通過創建一個事實來源來簡化這一點.
使用 webpack.DefinePlugin
我們可以設置 __static
變量僅在開發中 以生成指向 的路徑projectRoot>/static/
.如果您有多個 webpack
配置,您可以將其應用于 main
和 renderer
進程配置.
new webpack.DefinePlugin({'__static': `"${path.join(__dirname, '/static').replace(/\/g, '\\')}"`})
在生產環境中,我們需要在代碼中手動設置 __static
變量.這是我們可以做的...
index.html(渲染器
進程)
<!-- 為生產環境中的靜態文件設置`__static`路徑--><腳本>if (process.env.NODE_ENV !== 'development') window.__static = require('path').join(__dirname, '/static').replace(/\/g, '\\')</腳本><!-- 導入 webpack 包 -->
ma??in.js(main
進程)
//為生產環境中的靜態文件設置 `__static` 路徑if (process.env.NODE_ENV !== 'development') {global.__static = require('path').join(__dirname, '/static').replace(/\/g, '\\')}//下面的其余應用程序代碼
現在開始使用你的 __static
變量
假設我們有一個簡單的 JSON 文件,需要用 fs
讀取,這就是我們現在可以完成的事情......
static/someFile.json
{"foo":"bar"}
someScript.js
(renderer
或 main
進程)
從'fs'導入fs從路徑"導入路徑const someFile = fs.readFileSync(path.join(__static, '/someFile.json'), 'utf8')console.log(JSON.parse(someFile))//=>{ 富:酒吧 }
結論
webpack
用于將 require
d 或 import
ed 的資產捆綁到一個漂亮的捆綁包中.fs
或其他需要文件路徑的模塊引用的資源被視為靜態資源,webpack
不直接處理這些.使用 copy-webpack-plugin
和 webpack.DefinePlugin
我們可以設置一個可靠的 __static
變量,該變量會生成我們的 static/
開發和生產中的資產目錄.
最后,我個人還沒有看到任何其他 webpack
+ electron
樣板處理這種情況,因為這不是很常見的情況,但我認為我們可以所有人都同意在靜態資產目錄中擁有一個事實來源是緩解開發人員疲勞的絕妙方法.
I am using Webpack 2 and Electron to build nodejs application on Mac.
In my project in the root I have directory 'data' where I store configuration in a json like data/configurations/files.json (in practices there are different files with dynamic names)
After webpackaing though when I call: fs.readdirSync(remote.app.getAppPath());
to get files in the root I get only these packed: [ "default_app.js", "icon.png", "index.html", "main.js", "package.json", "renderer.js" ]
path.join(remote.app.getAppPath(), 'data/tests/groups.json');
called with FS ReadSync leads to an issue Error: ENOENT, data/tests/groups.json not found in /Users/myuser/myproject/node_modules/electron/dist/Electron.??app/Contents/Resourc??es/default_app.asar
. So it seems that the whole data folder is not picked up by webpacker.
Webpack config is using json-loader
and I did not find any documentation mentioning anything special about including specific files or jsons. Or do I have to reference json files in my code differently as they might be packed under main.js.
What is the best practice for Electron/Webpack for managing JSON config files? Am I doing something wrong when webpacking the project?
My project is based of https://github.com/SimulatedGREG/electron-vue using webpack/electron/vue
The Webpack Misconception
One thing to understand upfront is that webpack
does not bundle files required through fs
or other modules that ask for a path to a file. These type of assets are commonly labeled as Static Assets, as they are not bundled in any way. webpack
will only bundle files that are require
d or import
ed (ES6). Furthermore, depending on your webpack
configuration, your project root may not always match what is output within your production builds.
Based on the electron-vue documentation's Project Structure/File Tree, you will find that only webpack
bundles and the static/
directory are made available in production builds. electron-vue also has a handy __static
global variable that can provide a path to that static/
folder within both development and production. You can use this variable similar to how one would with __dirname
and path.join
to access your JSON files, or really any files.
A Solution to Static Assets
It seems the current version of the electron-vue boilerplate already has this solved for you, but I'm going to describe how this is setup with webpack
as it can apply to not only JSON files and how it can also apply for any webpack
+ electron
setup. The following solution assumes your webpack
build outputs to a separate folder, which we'll use dist/
in this case, assumes your webpack
configuration is located in your project's root directory, and assumes process.env.NODE_ENV
is set to development
during development.
The static/
directory
During development we need a place to store our static assets, so let's place them in a directory called static/
. Here we can put files, such as JSONs, that we know we will need to read with fs
or some other module that requires a full path to the file.
Now we need to make that static/
assets directory available in production builds.
But
webpack
isn't handling this folder at all, what can we do?
Let's use the simple copy-webpack-plugin
. Within our webpack
configuration file we can add this plugin when building for production and configure it to copy the static/
folder into our dist/
folder.
new CopyWebpackPlugin([
{
from: path.join(__dirname, '/static'),
to: path.join(__dirname, '/dist/static'),
ignore: ['.*']
}
])
Okay so the assets are in production, but how do I get a path to this folder in both development and production?
Creating a global __static
variable
What's the point of making this
__static
variable?
Using
__dirname
is not reliable inwebpack
+electron
setups. During development__dirname
could be in reference to a directory that exists in yoursrc/
files. In production, sincewebpack
bundles oursrc/
files into one script, that path you formed to get tostatic/
doesn't exist anymore. Furthermore, those files you put insidesrc/
that were notrequire
d orimport
ed never make it to your production build.When handling the project structure differences from development and production, trying to get a path to
static/
will be highly annoying during development having to always check yourprocess.env.NODE_ENV
.
So let's simplify this by creating one source of truth.
Using the webpack.DefinePlugin
we can set our __static
variable only in development to yield a path that points to <projectRoot>/static/
. Depending if you have multiple webpack
configurations, you can apply this for both a main
and renderer
process configuration.
new webpack.DefinePlugin({
'__static': `"${path.join(__dirname, '/static').replace(/\/g, '\\')}"`
})
In production, we need to set the __static
variable manually in our code. Here's what we can do...
index.html (renderer
process)
<!-- Set `__static` path to static files in production -->
<script>
if (process.env.NODE_ENV !== 'development') window.__static = require('path').join(__dirname, '/static').replace(/\/g, '\\')
</script>
<!-- import webpack bundle -->
main.js (main
process)
// Set `__static` path to static files in production
if (process.env.NODE_ENV !== 'development') {
global.__static = require('path').join(__dirname, '/static').replace(/\/g, '\\')
}
// rest of application code below
Now start using your __static
variable
Let's say we have a simple JSON file we need to read with fs
, here's what we can accomplish now...
static/someFile.json
{"foo":"bar"}
someScript.js
(renderer
or main
process)
import fs from 'fs'
import path from 'path'
const someFile = fs.readFileSync(path.join(__static, '/someFile.json'), 'utf8')
console.log(JSON.parse(someFile))
// => { foo: bar }
Conclusion
webpack
was made to bundle assets together that are require
d or import
ed into one nice bundle. Assets referenced with fs
or other modules that need a file path are considered Static Assets, and webpack
does not directly handle these. Using copy-webpack-plugin
and webpack.DefinePlugin
we can setup a reliable __static
variable that yields a path to our static/
assets directory in both development and production.
To end, I personally haven't seen any other webpack
+ electron
boilerplates handle this situation as it isn't a very common situation, but I think we can all agree that having one source of truth to a static assets directory is a wonderful approach to alleviate developer fatigue.
這篇關于如何管理 Webpack/Electron 應用程序的配置?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!