1

我有一个使用 webpack 4 构建的 React 项目。对于服务器端渲染,我构建了 express 后端并使用webpack-dev-middleware,webpack-hot-middlewarewebpack-hot-server-middleware. 此外,还有用于客户端和节点构建版本的 webpack 配置。但是,如果仅使用 webpack 命令单独启动,一切正常,但如果我想启动服务器,它会抛出以下结果:

<MY_SYSTEM_PATH>\node_modules\bootstrap\scss\bootstrap.scss:8
@import "functions";
^
SyntaxError: Invalid or unexpected token
    at new Script (vm.js:51:7)
    at createScript (vm.js:136:10)
    at Object.runInThisContext (vm.js:197:10)
    at Module._compile (module.js:613:28)
    at Module._extensions..js (module.js:660:10)
    at Object.require.extensions.(anonymous function) [as .js] (<MY_SYSTEM_PATH>\node_modules\babel-register\lib\node.js:152:7)
    at Module.load (module.js:561:32)
    at tryModuleLoad (module.js:501:12)
    at Function.Module._load (module.js:493:3)
    at Module.require (module.js:593:17)

bootstrap.scss 导入到 index.js 的 app 文件夹中,代码如下:

import React from 'react';
import 'bootstrap/scss/bootstrap.scss';

const App = () => {
    return(
      <div>
          <h1>React App!</h1>
          <div>
              <p>Just start!</p>
          </div>
      </div>
    );
};

export default App;

以下代码来自服务器的 webpack 配置:

module.exports = merge({
    name: 'server',
    target: "node",
    mode: 'development',
    entry: [
        'babel-regenerator-runtime',
        path.resolve(__dirname, '../src/server')
    ],
    output:{
        path: path.resolve(__dirname, '../public'),
        filename: "bundle.server.js",
        publicPath: "/",
        libraryTarget: "commonjs2"
    },
    module: {
        rules: [
            {
                test: /\.jsx?/,
                use: {
                    loader: 'babel-loader'
                },
                exclude:/node_modules/
            },
            {
                test:/\.scss/,
                use: [
                  {
                      loader: 'css-loader',
                      options: {
                          modules: true
                      }
                  },
                  {
                      loader: 'sass-loader'
                  }
                ]
            }
        ]
    }
}, commonConfig);

这是服务器开发配置:

const configs = [require('../../webpack/webpack.config.client.dev'), require('../../webpack/webpack.config.node.dev')];
const compilers = webpack(configs);

const publicPath = configs[0].output.publicPath;

// webpack-dev-middleware
app.use(require('webpack-dev-middleware')(compilers, { publicPath }))
// webpack-hot-middleware
app.use(require('webpack-hot-middleware')(compilers.compilers.find(c => c.name === 'client')));

// webpack-hot-server-middleware
const outputPath = configs[0].output.path;

app.use(publicPath, express.static(outputPath));

app.use(require('webpack-hot-server-middleware')(compilers, {
    serverRendererOptions: { outputPath },
}));

问题是:第一个代码块中出现错误的原因是什么以及如何解决?

4

0 回答 0