can webpack output separate script and module file

2020-07-23 06:55发布

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 = ).

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?

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",
   ...
}

1条回答
别忘想泡老子
2楼-- · 2020-07-23 07:29

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.

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'
      }
      ...
];

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.

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",
  ... 
}
查看更多
登录 后发表回答