gpt4 book ai didi

javascript - 使 Webpack 2.2.1 输出单个 JS 文件

转载 作者:行者123 更新时间:2023-11-30 15:32:53 25 4
gpt4 key购买 nike

我有一个非常简单的项目用来测试 webpack。针对我的代码运行时,我得到 2 个输出文件,0.bundle.js 和 bundle.js。

如何防止这种情况发生并让 webpack 只输出一个 js 文件?

文件夹结构

>- dist
>- node_modules
v- src
v- libs
BlackTriangle.js
app.js
index.html
main.js
package.json
webpack.config.js

webpack.config.js

var path = require("path"),
webpack = require("webpack");

module.exports = {
entry: "./src/main.js",
devtool: "source-map",
resolve: {
extensions: [ ".js", ],
modules: [ "node_modules", ],
alias: {
"BlackTriangle" : "./libs/BlackTriangle",
},
},
output: {
path: path.join(__dirname, "dist"),
filename: "main.js",
},
module: {
rules: [
{
test: /\.js$/,
loader: "babel-loader",
options: {
presets: ["es2015"],
},
},
],
},
};

index.html

<!DOCTYPE html>
<html>
<head>
<base href="/">
<meta charset="utf-8">
<title>Webpack Black Triangle</title>
<link rel="stylesheet" type="text/css" href="main.css">
<script type="text/javascript" data-main="main" src="node_modules/requirejs/require.js"></script>
</head>
<body>
<div id="triangle" class="BlackTriangle">
<div class="BlackTriangle-inner"></div>
</div>
</body>
</html>

ma​​in.js

//  Configure requirejs to work with external libraries
require.config({
//
baseUrl: "",
paths: {
"BlackTriangle" : "libs/BlackTriangle",
},
});


(function() {
"use strict";

// Call the main function when the page load has completed
if (document.readyState == "complete") {
main();
}
else if (window.addEventListener) {
window.addEventListener("load", main, false);
} else if (window.attachEvent) {
window.attachEvent("onload", main);
}
else
{
var oldOnload = window.onload;
window.onload = function() {
oldOnload();
main();
};
}

function main() {
require([ './app' ], function(app) {
app.init();
});
}
})();

app.js

define((require) => {
'use strict';

return {
init: () => {
const BlackTriangle = require("BlackTriangle");

const triangle = new BlackTriangle('#triangle');

window.setInterval(
() => {
triangle.rotate(1);
triangle.render();
},
20
);
},
};
});

BlackTriangle.js

define((require) => {
const blackTriangle = function(selector) {
this.angle = 0;
this.innerEl = document.querySelector(selector).querySelector('.BlackTriangle-inner');
};

blackTriangle.prototype.rotate = function(amount) {
this.angle = (this.angle + amount) % 360;
};

blackTriangle.prototype.render = function() {
this.innerEl.style.transform = `rotate(${this.angle}deg)`;
};

return blackTriangle;
});

最佳答案

您可以使用 LimitChunkCountPlugin 插件强制 webpack 只创建一个 block :

plugins: [
new webpack.optimize.LimitChunkCountPlugin({
maxChunks: 1, // disable creating additional chunks
})
],

关于javascript - 使 Webpack 2.2.1 输出单个 JS 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41991299/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com