【发布时间】:2021-05-19 16:56:39
【问题描述】:
我有一个静态 Javascript 项目(没有 react、vue 等),我正在尝试使用 webpack 转换、捆绑和缩小我的 js。我想在我的布局页面上有 bundle.js,其中将包括一堆在所有页面上运行的全局 js,然后是一个 page_x.js 文件,该文件将根据需要在各个页面上。 bundle.js 文件可能包含其他几个文件,应转译为 es5 并缩小。
在我当前的设置下,文件运行了两次。我不确定如何解决这个问题。我希望全局包含该文件,但也希望能够根据需要调用该函数。如果我从 page.js 中删除导入语句,则会收到控制台错误,“doSomething”未定义。如果我只在 page.html 上包含 page.js 而不是在 _layout.html 上包含 page.js,那么 common.js 只会在 page.html 上注销。我希望在每个页面上记录一次“common”,并且我希望 doSomething() 仅在 page.js 上可用。
这是一个运行两次的例子:
common.js
console.log("common");
export function doSomething() {
console.log("do something");
}
page.js
import {doSomething} from "/common.js";
$(button).click(doSomething);
页面加载(点击任何内容之前)的预期输出是:
"common"
我看到的是
"common"
"common"
我的 webpack.config.js 文件如下:
const path = require("path");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const RemoveEmptyScriptsPlugin = require("webpack-remove-empty-scripts");
const { CleanWebpackPlugin } = require("clean-webpack-plugin");
const WebpackWatchedGlobEntries = require("webpack-watched-glob-entries-plugin");
const CssnanoPlugin = require("cssnano");
const TerserPlugin = require("terser-webpack-plugin");
const dirName = "wwwroot/dist";
module.exports = (env, argv) => {
return {
mode: argv.mode === "production" ? "production" : "development",
entry: WebpackWatchedGlobEntries.getEntries(
[
path.resolve(__dirname, "src/scripts/**/*.js"),
path.resolve(__dirname, "src/scss/maincss.scss")
]),
output: {
filename: "[name].js",
path: path.resolve(__dirname, dirName)
},
devtool: "source-map",
module: {
rules: [
{
test: /\.s[c|a]ss$/,
use:
[
MiniCssExtractPlugin.loader,
"css-loader?sourceMap",
{
loader: "postcss-loader?sourceMap",
options: {
postcssOptions: {
plugins: [
CssnanoPlugin
],
config: true
},
sourceMap: true
}
},
{ loader: "sass-loader", options: { sourceMap: true } },
]
},
{
test: /\.(svg|gif|png|eot|woff|ttf)$/,
use: [
"url-loader",
],
},
{
test: /\.m?js$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: "babel-loader",
options: {
presets: ["@babel/preset-env"]
}
}
}
]
},
plugins: [
new WebpackWatchedGlobEntries(),
new CleanWebpackPlugin(),
new RemoveEmptyScriptsPlugin(),
new MiniCssExtractPlugin({
filename: "[name].css"
})
],
optimization: {
minimize: true,
minimizer: [
new TerserPlugin({
extractComments: false,
})
]
}
};
};
任何帮助将不胜感激。
【问题讨论】:
标签: javascript webpack bundle minify