背景
假设您有一个as 2015/ES6组件,其中有一个函数作为默认导出:
component.js
export default function() {
console.log("Hello, World!");
}一个应用程序,将其包含在:
app.js
import myComponent from "./component"
myComponent();和一个使用webpack开发中间件的Node.js/Express服务器,在app.js上运行Webpack (与Babel一起)并提供服务,并在以下内容中包括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问题
如何在两个component.js中以及在网络包装的app.js中使用app.js?
问题
实际上,该组件在app.js中运行良好,但是在尝试执行const component = require("./component")时会在节点控制台中抛出一个SyntaxError: Unexpected token export。
由于Babel只通过Webpack运行,而server.js是通过原始组件访问component.js,而不是绑定/转移组件,因此我们得到了错误。
我认为一个解决方案是运行两次Babel :在启动server.js之前在组件上运行一次,在Webpack中再运行一次,但这似乎非常不优雅和效率低下。
发布于 2018-05-10 15:18:53
我似乎无意中发现了一个可行的解决方案:用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 componenthttps://stackoverflow.com/questions/50261262
复制相似问题