当前位置: 首页 > 面试题库 >

如何将Webpack与Express一起使用?

汪耀
2023-03-14
问题内容

当我尝试将Webpack与简单的Express服务器一起使用时,总是会收到大量错误消息: express.js

'use strict';
var express = require('express');
var path = require('path');
var url = require('url');


// -------- my proxy----------------------
var app = express();
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.set('port', process.env.PORT || 8080);
app.use(function logErrors(err, req, res, next) {
        console.error(err.stack);
        next(err);
    }
);

app.listen(app.get('port'), function() {
    console.info('Express server started at http://localhost:' + app.get('port'));
});

我得到所有这些错误:

Version: webpack 1.10.0
Time: 1200ms
  Asset    Size  Chunks             Chunk Names
outfile  559 kB       0  [emitted]  main
chunk    {0} outfile (main) 498 kB [rendered]
    [0] ../app/server/express2.js 553 bytes {0} [built]
     + 125 hidden modules

WARNING in ../~/express/lib/view.js
Critical dependencies:
78:29-56 the request of a dependency is an expression
 @ ../~/express/lib/view.js 78:29-56

ERROR in ../~/express/lib/request.js
Module not found: Error: Cannot resolve module 'net' in /Users/Dynopia/Development/DS_Stalker_Frontend/node_modules/express/lib
 @ ../~/express/lib/request.js 18:11-25

ERROR in ../~/express/lib/view.js
Module not found: Error: Cannot resolve module 'fs' in /Users/Dynopia/Development/DS_Stalker_Frontend/node_modules/express/lib
 @ ../~/express/lib/view.js 18:9-22

ERROR in ../~/express/~/send/index.js
Module not found: Error: Cannot resolve module 'fs' in /Users/Dynopia/Development/DS_Stalker_Frontend/node_modules/express/node_modules/send
 @ ../~/express/~/send/index.js 25:9-22

ERROR in ../~/express/~/etag/index.js
Module not found: Error: Cannot resolve module 'fs' in /Users/Dynopia/Development/DS_Stalker_Frontend/node_modules/express/node_modules/etag
 @ ../~/express/~/etag/index.js 22:12-25

ERROR in ../~/express/~/send/~/destroy/index.js
Module not found: Error: Cannot resolve module 'fs' in /Users/Dynopia/Development/DS_Stalker_Frontend/node_modules/express/node_modules/send/node_modules/destroy
 @ ../~/express/~/send/~/destroy/index.js 1:17-30

ERROR in ../~/express/~/send/~/mime/mime.js
Module not found: Error: Cannot resolve module 'fs' in /Users/Dynopia/Development/DS_Stalker_Frontend/node_modules/express/node_modules/send/node_modules/mime
 @ ../~/express/~/send/~/mime/mime.js 2:9-22

ERROR in ../~/express/~/send/~/statuses/codes.json
Module parse failed: /Users/Dynopia/Development/DS_Stalker_Frontend/node_modules/express/node_modules/send/node_modules/statuses/codes.json Line 2: Unexpected token :
You may need an appropriate loader to handle this file type.
| {
|   "100": "Continue",
|   "101": "Switching Protocols",
|   "102": "Processing",
 @ ../~/express/~/send/~/statuses/index.js 2:12-35

ERROR in ../~/express/~/send/~/mime/types.json
Module parse failed: /Users/Dynopia/Development/DS_Stalker_Frontend/node_modules/express/node_modules/send/node_modules/mime/types.json Line 1: Unexpected token :
You may need an appropriate loader to handle this file type.

|
 @ ../~/express/~/send/~/mime/mime.js 87:12-35

ERROR in ../~/express/~/accepts/~/mime-types/~/mime-db/db.json
Module parse failed: /Users/Dynopia/Development/DS_Stalker_Frontend/node_modules/express/node_modules/accepts/node_modules/mime-types/node_modules/mime-db/db.json Line 2: Unexpected token :
You may need an appropriate loader to handle this file type.
| {
|   "application/1d-interleaved-parityfec": {
|     "source": "iana"
|   },
 @ ../~/express/~/accepts/~/mime-types/~/mime-db/index.js 11:17-37

ERROR in ../~/express/~/type-is/~/mime-types/~/mime-db/db.json
Module parse failed: /Users/Dynopia/Development/DS_Stalker_Frontend/node_modules/express/node_modules/type-is/node_modules/mime-types/node_modules/mime-db/db.json Line 2: Unexpected token :
You may need an appropriate loader to handle this file type.
| {
|   "application/1d-interleaved-parityfec": {
|     "source": "iana"
|   },
 @ ../~/express/~/type-is/~/mime-types/~/mime-db/index.js 11:17-37

这是我的配置文件:

var webpack = require('webpack');


module.exports = {
    // Makes sure errors in console map to the correct file
    // and line number
    devtool: 'eval',
    entry: [
        './bin/www.js'
    ],
    output: {
        path: './bin/out',
        filename: 'server.js'
    },

    extensions: [
        '',
        '.jsx', '.js'
    ],

    module: {

        loaders: [
            // Compile es6 to js.
            {
                test: /app\/.*\.js?$/,
                loaders: [
                    'react-hot',
                    'babel-loader'
                ]
            }
        ]
    },

    devtool: 'source-map'
};

我该怎么办,我还需要在服务器端使用webpack。

我像这样运行express.js文件: ./node_modules/webpack/bin/webpack.js ../app/server/express.js outfile --display-chunks -c --progress -d


问题答案:

我最终要做的是,我使用了两种不同的配置,一种用于使用webpack将服务器内容打包在一起,另一种用于将所有浏览器内容打包在一起,并且还运行webpack
dev服务器进行热重装。

*webpack.node.config.js 现在, *服务器Webpack配置 又看起来像这样:

var webpack = require('webpack');
var path = require('path');
var fs = require('fs');
var nodeModules = {};

// note the path.resolve(__dirname, ...) part
// without it, eslint-import-resolver-webpack fails
// since eslint might be invoked with different cwd
fs.readdirSync(path.resolve(__dirname, 'node_modules'))
    .filter(x => ['.bin'].indexOf(x) === -1)
    .forEach(mod => { nodeModules[mod] = `commonjs ${mod}`; });

// es5 style alternative
// fs.readdirSync(path.resolve(__dirname, 'node_modules'))
//     .filter(function(x) {
//         return ['.bin'].indexOf(x) === -1;
//     })
//     .forEach(function(mod) {
//         nodeModules[mod] = 'commonjs ' + mod;    
//     });

module.exports =

{
    // The configuration for the server-side rendering
    name: 'server',
    target: 'node',
    entry: './app/server/serverEntryPrototype.js',
    output: {
        path: './bin/',
        publicPath: 'bin/',
        filename: 'serverEntryPoint.js'
    },
    externals: nodeModules,
    module: {
        loaders: [
            { test: /\.js$/,

                loaders: [
                    // 'imports?document=this',

                    // 'react-hot',
                    'babel-loader'
                    //,'jsx-loader'
                ]
            },
            { test:  /\.json$/, loader: 'json-loader' },
        ]
    },
    plugins: [
    // new webpack.NormalModuleReplacementPlugin("^(react-bootstrap-modal)$", "^(react)$")
    // new webpack.IgnorePlugin(new RegExp("^(react-bootstrap-modal)$"))
    // new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/)
  ]
};

浏览器的WebPack配置 又名webpack.browser.config.js现在看起来是这样的:

var webpack = require('webpack');
var path = require('path');
var buildPath = path.resolve(__dirname, 'assets');
var fs = require('fs');


var commonLoaders = [
    { test: /\.js$/,

        loaders: [
            'react-hot',
            'babel-loader'
            //,'jsx-loader'
        ]
    }
];


module.exports =
{
    // Makes sure errors in console map to the correct file
    // and line number
    name: 'browser',
    devtool: 'eval',
    entry: [
        //'./bin/www.js',
        './app/index.js',
        'webpack/hot/dev-server',
        'webpack-dev-server/client?http://localhost:8081'  // WebpackDevServer host and port
    ],
    output: {
        path: buildPath,
        filename: '[name].js',
        // Everything related to Webpack should go through a build path,
        // localhost:3000/build. That makes proxying easier to handle
        publicPath: 'http://localhost:8081/assets/'
    },

    extensions: [
        '',
        '.jsx', '.js',
        '.json',
        '.html',
        '.css', '.styl', '.scss', '.sass'
    ],

    module: {

        loaders: [
            // Compile es6 to js.
            {
                test: /app\/.*\.jsx?$/,
                loaders: [
                    'react-hot',
                    'babel-loader'
                ]
            },

            ///app\/.*\.json$/
            { test:  /\.json$/, loader: 'json-loader' },

            // Styles
            { test: /\.css$/, loader: 'style-loader!css-loader' },
            { test: /\.s(a|c)ss$/, loader: 'style!css?localIdentName=[path][name]---[local]---[hash:base64:5]!postcss!sass' },

            // Fonts
            { test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/, loader: 'url-loader?limit=10000&minetype=application/font-woff' },
            { test: /\.(ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/, loader: 'file-loader' }

            //{ test: /\.png$/, loader: 'url-loader?limit=100000' },
            //{ test: /\.jpg$/, loader: 'file-loader' }
        ],

        plugins: [
            new webpack.HotModuleReplacementPlugin(),
            new webpack.NoErrorsPlugin()
        ]
    },

    postcss: [
        require('autoprefixer-core')
    ],

    devtool: 'source-map'
}
;


 类似资料:
  • 问题内容: 我用Webpack和react-rounter构建一个项目。这是我的代码: 当我请求时,就可以了!但是地址有误。查看错误消息:在此处输入图片描述 我的WebpackDevServer配置为: 我不知道怎么回事,帮帮我! 问题答案: 您正在使用相对路径来描述index.html中bundle.js的路径。 您应该在index.html中为bundle.js使用绝对路径 绝对路径包含根目录

  • 我正在尝试让web workers启动并运行Vue cli3,但我遇到了麻烦,无法让它正常工作。 我想使用下面的包worker-loader(而不是vue-worker),因为它看起来维护得很好,而且有更多的贡献。 在他们的教程之后,我尝试使用vue cli修改webpack,如下所示: 我希望能和他们的相配 可以在这里阅读(https://github.com/webpack-contrib/w

  • 我正在进行一个项目,在该项目中,我使用firebase函数中的express来运行使用手柄的服务器端渲染页面,一切都很正常,但当我使用firestore admin sdk时,我遇到以下错误: 我在函数/index.js文件中使用此代码 函数工作正常,但尝试const db=admin时。firestore()给了我一个错误。我还尝试了函数和firestore的模拟器,但仍然得到了相同的错误 请帮

  • 我在Ubuntu 14.04中安装了phpbrew以使用PHP5.4。它工作得很好,但当我尝试使用composer时除外,composer会忽略phpbrew并安装与PHP5.5相关的依赖项。 有没有办法强制composer与phpbrew config兼容?我试图在我的作曲家中添加:php:“5.4”。json,但是它说这个要求在我的php版本中是不可能的。

  • 我是Micronaut框架的新手,我正在尝试使用entitymanager创建我的存储库。我这样创建了我的存储库 我使用这个类实现接口并注入entitymanager 问题是我一直有这个错误: PS:我已经启用了注释处理

  • 我正在尝试将composer与我的WampServer一起使用。 我所有文件的路径都是,但当我运行composer时,它会将供应商文件和其他东西安装到其他地方。 我甚至不知道我的项目在哪里,我也不能改变我的项目在哪里的路径。我已经尝试了所有的方法,但它似乎仍然没有在我的项目文件夹中安装供应商文件。