可以为浏览器和节点webpack输出单独的脚本和模块文件? [英] can webpack output separate script and module files for browser and node?

查看:148
本文介绍了可以为浏览器和节点webpack输出单独的脚本和模块文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用webpack制作一个JavaScript对象,可以由浏览器加载(在脚本标签中),但我也希望webpack创建一个可以由节点加载的模块(需要 module .exports = )。

I am using webpack to make a JavaScript object that can be loaded by the browser (in a script tag) but I also want webpack to make a module that can be loaded by node (which needs module.exports = ).

有没有办法让webpack制作两个文件;例如 project.js project.node.js ?还是我走这个错误的方式?

Is there a way to get webpack to make two files; e.g. a project.js and project.node.js? Or am I going about this the wrong way?

D3 JavaScript库似乎是根据它的 package.json

The D3 JavaScript library seems to be doing something like this based on its package.json

{
  "main": "build/d3.node.js",
  "browser": "build/d3.js",
   ...
}


推荐答案

我发现如何获取webpack制作多个文件这里 - 基本上只是在 webpack.config.js 中导出对象数组而不只是一个。

I found how to get webpack to make multiple files here - basically just export an array of objects rather than just one in the webpack.config.js.

下面是 webpack.config.js 其中我使用相同的入口点 main.js 创建多个文件。

Below is the webpack.config.js where I am making multiple files using the same entry point main.js.

module.exports = [
  {
      entry: './src/main.js',
      output: {
        path: __dirname,
        filename: 'my_project.js',
        libraryTarget: 'var',
        library: 'my_project'
      },
      ... 
  },
  {
      entry: './src/main.js',
      output: {
        path: __dirname,
        filename: 'my_project.node.js',
        libraryTarget: 'commonjs2',
        library: 'my_project'
      }
      ...
];

我正在创建两个文件:1) my_project.js libraryTarget 设置为 var ,以便它可以由浏览器使用脚本标记加载和2 ) my_project.node.js libraryTarget 设置为 commonjs2 以便节点可以加载它。

I am making two files: 1) my_project.js with libraryTarget set to var so that the it can be loaded by the browser using a script tag and 2) my_project.node.js with libraryTarget set to commonjs2 so that node can load it.

我将 my_project.node.js 放在 package.json 中,以便webpack将加载它 - 见下面:

I put my_project.node.js under main in the package.json so that webpack would load it - see below:

{
  "name": "my_project",
  "version": "1.0.0",
  "description": "something ...",
  "main": "my_project.node.js",
  ... 
}

这篇关于可以为浏览器和节点webpack输出单独的脚本和模块文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆