我有一个非常简单的项目,我用来测试webpack。当我的代码运行时,我得到2个输出文件,0bundle.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>
main.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;
});
答案 0 :(得分:2)
您可以使用LimitChunkCountPlugin
插件强制webpack只创建一个块:
plugins: [
new webpack.optimize.LimitChunkCountPlugin({
maxChunks: 1, // disable creating additional chunks
})
],
答案 1 :(得分:0)
使用instead
中的require
来解决我项目中的问题(感谢@GetFuzzy)
之前:
require(["jquery"], function($) {
...
});
之后:
define(["jquery"], function($) {
...
});