我在下面的链接上添加了一个模板/样板文件:
https://github.com/tarunlalwani/electron-webpack-typescript-boilerplate
因此,想法是将代码分为3个文件夹。
src
|
|
|
主进程的代码将在main
文件夹中,UI/渲染器的代码将在renderer
文件夹中。
现在,您想在两者中都使用TypeScript
并拥有2个webpack配置文件,一个用于打包main
,另一个用于打包renderer
。
const path = require('path');
console.log(__dirname);
let common_config = {
node: {
__dirname: true
},
mode: process.env.ENV || 'development',
module: {
rules: [
{
test: /\.tsx?$/,
use: 'ts-loader',
exclude: [
/node_modules/,
path.resolve(__dirname, "src/ui")
]
}
]
},
resolve: {
extensions: [ '.tsx', '.ts', '.js' ]
},
};
module.exports = [
Object.assign({}, common_config, {
target: 'electron-main',
entry: {
renderrer: './src/main/index.ts',
},
output: {
filename: '[name]-bundle.js',
path: path.resolve(__dirname, 'src/main/dist')
},
}),
Object.assign({}, common_config, {
target: 'electron-renderer',
entry: {
ui: './src/renderer/index.ts',
},
output: {
filename: '[name]-bundle.js',
path: path.resolve(__dirname, 'src/renderer/dist')
},
})
]
人们面临的另一个问题是,如果不采取措施,__dirname
将变为 /
。因此,我们在 webpack 配置中包含以下内容:
node: {
__dirname: true
},
这确保了相对路径的可用性。现在我们可以在开发环境中使用os.cwd()
,在生产中使用process.resourcePath
。更多细节请参见下面的讨论
如何使用 Electron 运行和打包外部可执行文件?
webpack 配置的目标需要不同。因此,对于主要的配置,我们使用electron-main
,对于渲染器,我们使用electron-renderer
renderer/tsconfig.json
tsconfig.json
对于main
和renderer
需要不同,并且应该互相排除。所以我们使用上面的配置。
{
"compileOnSave": false,
"compilerOptions": {
"target": "es2015",
"moduleResolution": "node",
"pretty": true,
"newLine": "LF",
"allowSyntheticDefaultImports": true,
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"sourceMap": true,
"skipLibCheck": true,
"allowJs": true,
"jsx": "preserve"
},
"exclude": [
"node_modules",
"src/main"
]
}
主要/tsconfig.json
{
"compileOnSave": false,
"compilerOptions": {
"target": "es2015",
"moduleResolution": "node",
"pretty": true,
"newLine": "LF",
"allowSyntheticDefaultImports": true,
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"sourceMap": true,
"skipLibCheck": true,
"allowJs": true,
"jsx": "preserve"
},
"exclude": [
"node_modules",
"src/renderer"
]
}
最后一个主要的事情是你的 package.json
,如下所示
{
"name": "boilerplate",
"version": "1.0.0",
"main": "src/main/dist/renderrer-bundle.js",
"license": "MIT",
"scripts": {
"start": "npm-run-all build run-electron",
"build": "webpack --config webpack.config.js",
"run-electron": "electron ."
},
"dependencies": {
"electron": "^1.8.2",
"jquery": "^3.3.1",
"typescript": "^2.7.2",
"webpack": "^4.0.1"
},
"devDependencies": {
"@types/electron": "^1.6.10",
"@types/jquery": "^3.3.0",
"@types/node": "^9.4.6",
"html-webpack-plugin": "^2.30.1",
"npm-run-all": "^4.1.2",
"ts-loader": "^4.0.0",
"tslint": "^5.9.1",
"webpack-cli": "^2.0.9"
}
}
这会让你入门,然后在学习过程中,你可以添加像 tslint
,jslint
这样的东西