如何使用Webpack5打包另一个js文件?

huangapple go评论67阅读模式
英文:

How to packed another js file using Webpack5?

问题

我是webpack的新手。

我有2个javascript文件,我想将其中一个用作入口文件。至于另一个文件,我不希望所有的HTML都使用它,我只会在一些特定的文件中使用它。

例如,如您所见,下面是文件结构,main.js 是我的入口文件。还有另一个名为 123.js 的js文件。我希望 1.html 使用 main.js123.js。然而,./2.html 只需要 ./main.js

文件结构:

./main.js
./123.js
./1.html
./2.html

如何实现这一点?
谢谢。

英文:

I am a newcomer to webpack.

I have 2 javascript files and I want to use one as the entry file. For another I don't want all the html use it, I'll use it in some specify files.

For exmaple, as you can see the file structure below ,main.js is my entry file. And there is another js file called 123.js. I expect that 1.html uses both main.js and 123.js. However, the ./2.html only need `./main.js

File Structure:

./main.js
./123.js
./1.html
./2.html

How to implement this?
Thanks.

答案1

得分: 1

你可以使用HtmlWebpackPlugin

你的webpack配置可以类似如下:

const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  entry: {
    main: './main.js',
    oneTwoThree: './123.js'
  },
  plugins: [
    new HtmlWebpackPlugin({
      filename: '1.html',
      chunks: ['main', 'oneTwoThree']
    }),
    new HtmlWebpackPlugin({
      filename: '2.html',
      chunks: ['main']
    })
  ],
  output: {
    filename: '[name].js',
    path: path.resolve(__dirname, 'dist'),
  },
};
英文:

You can use HtmlWebpackPlugin

Your webpack configuration could look something like this:
<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const HtmlWebpackPlugin = require(&#39;html-webpack-plugin&#39;);

module.exports = {
  entry: {
    main: &#39;./main.js&#39;,
    oneTwoThree: &#39;./123.js&#39;
  },
  plugins: [
    new HtmlWebpackPlugin({
      filename: &#39;1.html&#39;,
      chunks: [&#39;main&#39;, &#39;oneTwoThree&#39;]
    }),
    new HtmlWebpackPlugin({
      filename: &#39;2.html&#39;,
      chunks: [&#39;main&#39;]
    })
  ],
  output: {
    filename: &#39;[name].js&#39;,
    path: path.resolve(__dirname, &#39;dist&#39;),
  },
};

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年7月28日 02:24:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/76782493.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定