【发布时间】:2017-12-02 00:33:04
【问题描述】:
我正在尝试使用 React.js 前端构建一个 Web 应用程序,Express 处理后端,Webpack 捆绑整个事情。我正在尝试摆脱为服务器和客户端创建单独的 webpack.config 文件的习惯方式。我也在尝试添加一个缩小器(Babili)。
这是我的 webpack.config 文件。请注意我如何使用 object.assign 为我的客户端和服务器文件创建不同的对象,以及我如何在最后导出它们。我怀疑这就是问题所在。
const BabiliPlugin = require('babili-webpack-plugin');
const nodeExternals = require('webpack-node-externals');
const path = require('path');
const srcPath = path.resolve(__dirname + '/src');
const distPath = path.resolve(__dirname + '/dist');
// Common entries for all configs
var common = Object.assign({}, {
context: srcPath,
resolve: {
modules: ['node_modules', 'src'],
extensions: ['*']
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader'
}
]
},
plugins: [
new BabiliPlugin()
],
externals: nodeExternals()
});
// Server.js config
// Output to dist/client/
var serverConfig = Object.assign({}, common, {
entry: './server/index.js',
output: {
path: distPath,
filename: 'server.min.js'
},
target: 'node',
node: {
__dirname: false,
__filename: false
}
});
// Client.js config
// Output to /dist/
var clientConfig = Object.assign({}, common, {
entry: "./client/index.js",
output: {
path: distPath,
filename: './client/client.min.js',
publicPath: '/'
},
target: 'web',
devtool: 'source-map'
});
// Export configurations array
module.exports = [serverConfig, clientConfig]
这是我的 client.js 文件:
import React from 'react';
import ReactDOM from 'react-dom';
import { Router, Route } from 'react-router-dom';
import Home from './routes/Home.js';
ReactDOM.render((
<div>
<p> why is this not working </p>
</div>
), document.getElementById('app'));
我在浏览器控制台中得到的错误如下:
Uncaught ReferenceError: require is not defined
at Object.<anonymous> (client.min.js:1)
at b (client.min.js:1)
at Object.<anonymous> (client.min.js:1)
at b (client.min.js:1)
at client.min.js:1
at client.min.js:1
我不明白为什么它不起作用。 server.js 文件工作正常,因为我可以看到 index.html 文件已提供给浏览器。我通常使用的 webpack.config 文件与 Babili 压缩器完全相同,但删除它并不能解决问题。我希望你们能帮助我解决这个问题。提前谢谢!
编辑:我想补充一点,我之前的客户端配置中没有 nodeExternals() 部分。但是,当我不包含它时,会出现以下错误:
Uncaught Error: Cannot find module "object-assign"
at client.min.js:8
at client.min.js:8
at Object.<anonymous> (client.min.js:8)
at Object.<anonymous> (client.min.js:8)
at t (client.min.js:1)
at Object.<anonymous> (client.min.js:1)
at Object.<anonymous> (client.min.js:1)
at t (client.min.js:1)
at Object.<anonymous> (client.min.js:1)
at t (client.min.js:1)
【问题讨论】:
-
你能把
index.html文件的代码贴出来吗? -
index.html文件只有一个和一个
标签: javascript reactjs webpack ecmascript-6 babeljs