[英]Webpack output file to have exports default instead of module.exports
I have a case where I need webpack to create a file using export
syntax and not module.exports
. 我有一种情况,我需要webpack使用
export
语法而不是module.exports
创建文件。 Is this possible? 这可能吗?
Here's my config: 这是我的配置:
const path = require('path');
module.exports = {
mode: "production",
entry: "./node/example.js",
node: {
console: true,
global: true,
process: true,
__filename: true,
__dirname: true,
Buffer: true,
setImmediate: true,
},
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'example.js',
libraryTarget: 'commonjs-module'
},
resolve: {
// options for resolving module requests
// (does not apply to resolving to loaders)
modules: [
"node_modules",
path.resolve(__dirname, "app")
],
// directories where to look for modules
extensions: [".js", ".ts", ".jsx", ".css"],
},
target: "node", // enum // the environment in which the bundle should run
}
example.js looks like this:
example.js看起来像这样:
module.exports = function() {
return 'hello world';
}
What I need webpack to do is export with export default
rather then module.exports =
. 我需要webpack进行的工作是使用
export default
而不是module.exports =
export default
。
You can use a transpiler (like Babel) to allow you to use language features that aren't supported by your runtime environment (like import
and export
syntax). 您可以使用翻译器(例如Babel)来使用运行时环境不支持的语言功能(例如
import
和export
语法)。 You can install the required modules with 您可以使用安装以下模块
npm i @babel/core @babel/preset-env babel-loader
That installs the Babel core, a plugin which transpiles future language features, and the webpack loader to pre-process JS files with Babel. 这将安装Babel核心,一个可转换未来语言功能的插件,以及webpack加载程序以使用Babel预处理JS文件。
Then, you'll need a .babelrc
config file in your root project directory. 然后,在根项目目录中需要一个
.babelrc
配置文件。 In this case it just needs to contain the following 在这种情况下,它只需要包含以下内容
{"presets": ["@babel/preset-env"]}
That tells Babel you want to use the "preset env." 这告诉Babel您要使用“预设环境”。 plugin to transpile your
import
and export
statements, among other things. 该插件可转换您的
import
和export
语句等。
Finally, you need to tell Webpack to use Babel to load JS files. 最后,您需要告诉Webpack使用Babel加载JS文件。 You can do this by adding a
module.rules
list to your Webpack config like so. 您可以通过如下方式将
module.rules
列表添加到Webpack配置中来实现。
node: { /* ... */ },
module: {
rules: [
{test: /\.js$/, use: 'babel-loader'}
]
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.