反应+电子应用问题>无法加载资源:net :: err_file_not_found bg.jpg

时间:2018-05-14 14:03:05

标签: javascript reactjs electron

当我在不使用本地服务器的情况下构建电子应用程序或尝试使用电子打包器打包应用程序时,它显示了我

  

Blockquote无法加载资源:net :: err_file_not_found bg.jpg

然而,当我使用本地服务器“快递”时,该应用程序运行正常。 如何解决该问题以使用所有资源打包应用程序

这是webpack.config

const path = require('path');
const webpack = require('webpack');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
process.env.NODE_ENV = process.env.NODE_ENV || 'development';

if (process.env.NODE_ENV === 'test') {
  require('dotenv').config({ path: '.env.test' });
} else if (process.env.NODE_ENV === 'development') {
  require('dotenv').config({ path: '.env.development' });
}

module.exports = (env) => {
  const isProduction = env === 'production';
  const CSSExtract = new ExtractTextPlugin('styles.css');

  return {
    target:"electron-renderer",
    entry: ['babel-polyfill', './src/app.js'],
    output: {
      path: path.join(__dirname, 'public', 'dist',),
      filename: 'bundle.js',
    },
    module: {
      rules: [{
        loader: 'babel-loader',
        test: /\.js$/,
        exclude: /node_modules/
      }, {
        test: /\.s?css$/,
        use: CSSExtract.extract({
         // publicPath:'./',
          use: [
            {
              loader: 'css-loader',
              options: {
                sourceMap: true
              }
            },
            {
              loader: 'sass-loader',
              options: {
                sourceMap: true
              }
            }
          ]
        })
      }]
    },
    plugins: [
      CSSExtract
    ],
    devtool: isProduction ? 'source-map' : 'inline-source-map',
    devServer: {
      contentBase: path.join(__dirname, 'public'),
      historyApiFallback: true,
      publicPath: '/dist/'
    }
  };
};

,这是电子的Index.js

//import electronGoogleOauth from 'electron-google-oauth';
const electron = require('electron')
const app = electron.app
const BrowserWindow = electron.BrowserWindow

const url = require('url');

// Module to control application life.

// Module to create native browser window.
const path = require('path');
const fs = require('fs');
const os = require('os');
const ipc = electron.ipcMain;
const shell = electron.shell;
// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let mainWindow;
let workerWindow;


/** This function will create the mainWindow */
function createWindow() {
  console.log('hello world')

  // Create the browser window.
  mainWindow = new BrowserWindow({ 
    titleBarStyle: 'hidden',
    width: 950,
    height: 750,
    'minHeight':700,
    'minWidth': 950,
    icon:path.join(__dirname,'./src/assets/icons/icon.ico'),
   });

  // and load the index.html of the app.
  //mainWindow.loadURL('http://localhost:3000/public/index.html');
  mainWindow.loadURL('http://localhost:3000/public/index.html');

  ////////////////////////////////////////// Invisible Window //////////
  workerWindow = new BrowserWindow();
    workerWindow.loadURL(`file://${__dirname}/worker.html`);
    //workerWindow.hide();
    workerWindow.webContents.openDevTools();
    workerWindow.on("closed", () => {
        workerWindow = undefined;
    });

  ///////////////////////////////////////////////////////////////



  if (process.env.NODE_ENV === 'development') {
    // Open the DevTools.
    mainWindow.webContents.openDevTools();
    const {
      default: installExtension,
      REACT_DEVELOPER_TOOLS,
      REDUX_DEVTOOLS,
    } = require('electron-devtools-installer'); // eslint-disable-line
    installExtension(REACT_DEVELOPER_TOOLS)
      .then(name => console.log(`Added Extension:  ${name}`))
      .catch(err => console.log('An error occurred: ', err));

    installExtension(REDUX_DEVTOOLS)
      .then(name => console.log(`Added Extension:  ${name}`))
      .catch(err => console.log('An error occurred: ', err));
  }

  // Emitted when the window is closed.
  mainWindow.on('closed', () => {
    // Dereference the window object, usually you would store windows
    // in an array if your app supports multi windows, this is the time
    // when you should delete the corresponding element.
    mainWindow = null;
  });
}

ipc.on("printPDF",(event, content) => {
    workerWindow.webContents.send("printPDF", content);
});


// when worker window is ready
ipc.on("readyToPrintPDF", (event) => {
  const pdfPath = path.join(os.tmpdir(), 'print.pdf');
  // Use default printing options
  workerWindow.webContents.printToPDF({}, function (error, data) {
      if (error) throw error
      fs.writeFile(pdfPath, data, function (error) {
          if (error) {
              throw error
          }
    console.log(2)
          shell.openItem(pdfPath)
          event.sender.send('wrote-pdf', pdfPath)

      })
  })

});
///////////////////////////////////////////////////////
ipc.on('print-to-pdf', function(event){
  const pdfPath = path.join(os.tmpdir(),'print.pdf');
  const win = BrowserWindow.fromWebContents(event.sender);
  win.webContents.printToPDF({},function(error,data){
    if(error) return console.log(error.message)
    fs.writeFile(pdfPath,data, function(err){
      if(err)return console.log(err.message);
      shell.openExternal('file://'+pdfPath);
      event.sender.send('wrote-pdf',pdfPath)
    })
  })
})
///////////////////////////////////////////////////////

app.on('ready', createWindow);

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit();
  }
});

app.on('activate', () => {
  if (mainWindow === null) {
    createWindow();
  }
});

的index.html

    <html> 
    <head>
      <meta http-equiv="Content-type" content="text/html; charset=UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <title>My electron app</title>
      <link rel="icon" type="image/png" href="images/favicon.png" />
      <link rel="stylesheet" type="text/css" href="/dist/styles.css" />
    </head>

<body style="-webkit-print-color-adjust:exact;">
  <div id="app"></div>
  <script src="/dist/bundle.js"></script>
</body>
</html>

0 个答案:

没有答案