账号密码登录
微信安全登录
微信扫描二维码登录

登录后绑定QQ、微信即可实现信息互通

手机验证码登录
找回密码返回
邮箱找回 手机找回
注册账号返回
其他登录方式
分享
  • 收藏
    X
    electron-vue webview js 文件打包出的代码浏览器不能识别?
    • 2019-04-09 00:00
    • 11
    65
    0

    想在electron-vue 项目中实现打印功能,想采用渲染进程与webview通信的方式实现,webview也是用vue写,现在碰到一个问题,webview 的js 打包出来后是module.exports = ........这样的代码,浏览器环境识别不了

    webview 的js 代码 print.js

    import Vue from 'vue'
    import axios from 'axios'
    
    import Pw from './pw'
    // import router from './router'
    // import store from './store'
    
    if (!process.env.IS_WEB) Vue.use(require('vue-electron'))
    Vue.http = Vue.prototype.$http = axios
    Vue.config.productionTip = false
    
    /* eslint-disable no-new */
    new Vue({
        components: { Pw },
        // router,
        // store,
        template: '<Pw/>'
    }).$mount('#print')

    print.js 中 引入的 vue 代码

    <template>
        <div>this is vue webvue</div>
    </template>
    
    <script>
        export default {
            name: 'pw'
        }
    </script>
    
    <style>
        /* CSS */
    </style>

    webview 的打包代码 webpack.webview.config.js

    'use strict'
    
    process.env.BABEL_ENV = 'renderer'
    
    const path = require('path')
    const { dependencies } = require('../package.json')
    const webpack = require('webpack')
    
    const BabiliWebpackPlugin = require('babili-webpack-plugin')
    const CopyWebpackPlugin = require('copy-webpack-plugin')
    const MiniCssExtractPlugin = require('mini-css-extract-plugin')
    const HtmlWebpackPlugin = require('html-webpack-plugin')
    const { VueLoaderPlugin } = require('vue-loader')
    
    let whiteListedModules = ['vue']
    
    let webviewConfig = {
        devtool: '#cheap-module-eval-source-map',
        entry: {
            print: path.join(__dirname, '../src/renderer/print.js')
        },
        externals: [
            ...Object.keys(dependencies || {}).filter(d => !whiteListedModules.includes(d))
        ],
        module: {
            rules: [
                {
                    test: /\.(js|vue)$/,
                    enforce: 'pre',
                    exclude: /node_modules/,
                    use: {
                        loader: 'eslint-loader',
                        options: {
                            formatter: require('eslint-friendly-formatter')
                        }
                    }
                },
                {
                    test: /\.scss$/,
                    use: ['vue-style-loader', 'css-loader', 'sass-loader']
                },
                {
                    test: /\.sass$/,
                    use: ['vue-style-loader', 'css-loader', 'sass-loader?indentedSyntax']
                },
                {
                    test: /\.less$/,
                    use: ['vue-style-loader', 'css-loader', 'less-loader']
                },
                {
                    test: /\.css$/,
                    use: ['vue-style-loader', 'css-loader']
                },
                {
                    test: /\.html$/,
                    use: 'vue-html-loader'
                },
                {
                    test: /\.js$/,
                    use: 'babel-loader',
                    exclude: /node_modules/
                },
                {
                    test: /\.node$/,
                    use: 'node-loader'
                },
                {
                    test: /\.vue$/,
                    use: {
                        loader: 'vue-loader',
                        options: {
                            extractCSS: process.env.NODE_ENV === 'production',
                            loaders: {
                                sass: 'vue-style-loader!css-loader!sass-loader?indentedSyntax=1',
                                scss: 'vue-style-loader!css-loader!sass-loader',
                                less: 'vue-style-loader!css-loader!less-loader'
                            }
                        }
                    }
                },
                {
                    test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
                    use: {
                        loader: 'url-loader',
                        query: {
                            limit: 10000,
                            name: 'imgs/[name]--[folder].[ext]'
                        }
                    }
                },
                {
                    test: /\.(mp4|webm|ogg|mp3|wav|flac|aac)(\?.*)?$/,
                    loader: 'url-loader',
                    options: {
                        limit: 10000,
                        name: 'media/[name]--[folder].[ext]'
                    }
                },
                {
                    test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
                    use: {
                        loader: 'url-loader',
                        query: {
                            limit: 10000,
                            name: 'fonts/[name]--[folder].[ext]'
                        }
                    }
                }
            ]
        },
        node: {
            __dirname: process.env.NODE_ENV !== 'production',
            __filename: process.env.NODE_ENV !== 'production'
        },
        plugins: [
            new VueLoaderPlugin(),
            new MiniCssExtractPlugin({filename: 'styles.css'}),
            new HtmlWebpackPlugin({
                filename: 'printer.html',
                template: path.resolve(__dirname, '../src/printer.html'),
                minify: {
                    collapseWhitespace: true,
                    removeAttributeQuotes: true,
                    removeComments: true
                },
                nodeModules: process.env.NODE_ENV !== 'production'
                    ? path.resolve(__dirname, '../node_modules')
                    : false
            }),
            // new webpack.HotModuleReplacementPlugin(),
            // new webpack.NoEmitOnErrorsPlugin()
        ],
        output: {
            filename: '[name].js',
            libraryTarget: 'commonjs2',
            path: path.join(__dirname, '../dist/electron')
        },
        resolve: {
            alias: {
                '@': path.join(__dirname, '../src/renderer'),
                'vue$': 'vue/dist/vue.esm.js'
            },
            extensions: ['.js', '.vue', '.json', '.css', '.node']
        },
        target: 'electron-renderer'
    }
    
    
    
    module.exports = webviewConfig
    

    babel 配置文件 .babelrc

    {
      "presets": ["babel-preset-env"]
    }

    打包出来的文件是

    module.exports=function(n){  ...........  }

    报错 module is not defined

    如何让这个webview 的js 代码正确打包成让浏览器可识别的js

    0
    打赏
    收藏
    点击回答
    您的回答被采纳后将获得:提问者悬赏的 11 元积分
        全部回答
    • 0
    • 一芈孑の孤单 普通会员 1楼

      在Electron-vue Webview JavaScript 文件打包并打包成HTML5 Webpack bundle时,如果浏览器无法识别代码,可能有以下几种原因:

      1. 文件格式问题:Webpack会自动将JavaScript文件打包为JavaScript文件,但这种格式在现代浏览器中可能并不被所有浏览器支持。例如,ES6语法在Webview中可能被忽略,或者在一些老版本的浏览器中可能被浏览器限制。你可以尝试使用ES5的ES6语法来编写JavaScript代码,或者使用浏览器内置的polyfill库来解决兼容性问题。

      javascript // 使用ES6语法编写JavaScript代码 const Vue = require('vue'); new Vue({ el: '#app', render: h => h(App) }).$mount('#app');

      1. 浏览器禁用:某些浏览器可能禁用了Webview的JavaScript功能,如polyfills或浏览器内置的console.log()方法。你可以在HTML文件中添加相关JavaScript代码,以在Webview中运行JavaScript代码。例如:

      ```html

      Webview JavaScript Example

      ```

      1. 浏览器插件或扩展:在Electron中,Webview并不支持一些浏览器插件或扩展,如Safari的WKWebView。你可能需要安装并配置这些插件,以使Webview支持JavaScript功能。以下是一个示例:

      ```javascript // 安装Safari Webview插件 const SafariWebviewPlugin = require('safari-webview-plugin');

      // 初始化Safari Webview const safari = new SafariWebviewPlugin();

      // 加载HTML文件 safari.load('index.html');

      // 设置页面视口 safari.setWebviewHeight(600); safari.setWebviewWidth(800);

      // 在Webview中运行JavaScript代码 safari.run('main.js'); ```

      1. 文件内容错误:Webview加载的HTML文件内容可能包含JavaScript代码,但浏览器可能无法解析或识别这些代码。在Electron中,你可以通过使用file-loader模块来处理HTML文件中的JavaScript内容。例如:

      ```javascript import { fileLoader } from 'file-loader';

      // 创建file-loader实例 const fileLoaderOptions = { filename: 'index.html', publicPath: 'path/to/index.html', encoding: 'utf-8' };

      fileLoader.loaders.push(fileLoaderOptions);

      // 在Webview中加载HTML文件 fileLoader.queue('index.html', { context: safari });

      // 在Webview中运行JavaScript代码 safari.run('main.js'); ```

      1. 兼容性问题:如果你的Webview代码包含ES6语法,但浏览器未支持,你可能需要添加相应的polyfill库,如babel-polyfill,来确保代码的正确执行。例如:

      ```javascript // 安装babel-polyfill const polyfill = require('babel-polyfill');

      // 加载ES6语法代码 const code = ` const myFunction = () => { console.log('Hello, World!'); };

      myFunction(); `;

      // 在Webview中运行JavaScript代码 polyfill(code); ```

      以上就是解决Electron-vue Webview JavaScript 文件打包出的代码浏览器不能识别问题的一些常见方法。请根据实际情况选择合适的方法,确保Webview能够正确运行你的JavaScript代码。

    更多回答
    扫一扫访问手机版
    • 回到顶部
    • 回到顶部