在应用程序和 Node 中使用 ES6 模块,同时使用 Webpack-Dev-Middleware 和 Express

Using an ES6 module in both an app and in Node, while using Webpack-Dev-Middleware and Express

背景

假设您有一个 ES2015/ES6 组件,其中一个函数作为默认导出:

component.js

export default function() {
    console.log("Hello, World!");
}

将其包含在的应用程序:

app.js

import myComponent from "./component"

myComponent();

和一个 Node.js/Express 服务器使用 webpack-dev-middleware,到 运行 Webpack(带 Babel)并提供服务 app.js,以及 包括 component.js 在:

server.js

const express = require("express");
const app = express();

// start the server
app.listen(process.env.EXPRESS_PORT, () => {
    console.log(`App listening on port ${process.env.EXPRESS_PORT}!`);
});

const webpack = require("webpack");
const webpackConfig = require("./webpack.config");
const compiler = webpack(webpackConfig);

// use webpack-dev-middleware to serve the publicPath
app.use(
    require("webpack-dev-middleware")(compiler, {
        logLevel: "warn",
        publicPath: webpackConfig.output.publicPath,
    })
);

// use webpack-hot-middleware for HMR
app.use(require("webpack-hot-middleware")(compiler));

const myComponent = require("./component") // import the component
myComponent(); // use the component

问题

您如何在 server.js 以及 Webpacked app.js 中使用 component.js

问题

按原样,该组件在 app.js 中运行良好,但在尝试执行 const component = require("./component") 时在节点控制台中抛出 SyntaxError: Unexpected token export

由于 Babel 仅通过 Webpack 运行,并且 server.js 通过原始组件而不是 bundled/transpiled 访问 component.js,我们得到了错误。

我想一个解决方案是 运行 Babel 两次:一次是在 server.js 启动之前在组件上,一次是在 Webpack 中,但这看起来非常不优雅且效率低下。

我似乎偶然发现了一个可行的解决方案:以 CommonJS 格式编写模块,Webpack/Babel 将为 ES6 编译它。

工作文件:

component.js

function myComponent() {
    console.log("Hello, World!");
}

module.exports = { myComponent };

app.js

import myComponent from "./component"

myComponent();

server.js

const { myComponent } = require("./component") // import the component

myComponent(); // use the component