javascript - WebPack output.library.type var 未定义
问题描述
我正在使用简码学习 WebPack。在代码中,我们试图计算立方和平方。他们将假设按照以下 webpack.config.js 存储在一个变量中。
const webpack = require('webpack');
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const isDevelopment = process.env.NODE_ENV === 'development';
const config = {
entry: './src/index.ts',
output: {
path: path.resolve(__dirname, 'dist'),
library: {
type: 'var',
name: 'testVar'
},
filename: '[name].js'
},
mode: 'production',
plugins: [
new MiniCssExtractPlugin({
// Options similar to the same options in webpackOptions.output
// both options are optional
filename: "[name].css",
chunkFilename: "[id].css",
}),
new webpack.optimize.LimitChunkCountPlugin({
maxChunks: 1,
}),
new HtmlWebpackPlugin({
hash: true,
title: 'Video Player Play Ground',
myPageHeader: 'Sample Video Player',
template: './src/index.html',
filename: 'index.html'
})
],
module: {
rules: [
{
test: /\.s[ac]ss$/i,
exclude: /node_modules/,
use: [
// fallback to style-loader in development
MiniCssExtractPlugin.loader,
"css-loader",
"sass-loader",
],
},
{
test: /\.ts(x)?$/,
loader: 'ts-loader',
exclude: /node_modules/
},
{
test: /\.svg$/,
use: 'file-loader'
}
]
},
resolve: {
extensions: [
'.tsx',
'.ts',
'.js',
'.scss'
]
},
optimization: {
usedExports: true,
runtimeChunk: false,
minimize: false
}
};
module.exports = config;
如上面的配置所示,我们将编译后的 javascript 存储在名为“testVar”的变量中。
当我们使用以下命令行代码“webpack --mode production”时,上述方法工作正常
在最终生成的 javascript 文件中,我们有一行等于 testVar = webpack_exports;
此外, testVar.start 工作正常。
但是当我们使用以下命令行“webpack serve --mode production”或“webpack serve”运行本地服务器时,上述方法不起作用,testVar.start 是未定义的。我不确定我做错了什么。
以下是我们在 index.html 文件中使用的代码来调用我们在内部 javascript 中定义的 start 函数
window.onload = function (){
alert(testVar);
console.log(testVar);
if(testVar.start !== undefined)
{
alert(testVar.start);
console.log(testVar.start);
testVar.start(3,2);
}
else {
alert("Start Function is undefined");
}
}
以下是来自 index.ts 和 math.ts 的代码洞察。
import {cube, square} from './math';
export function start(c:number, s:number) {
console.log(cube(c));
console.log(square(s));
}
export function square(x:number) {
return x * x;
}
export function cube(x:number) {
return x * x * x;
}
解决方案
最后,我让它工作了:-)。我需要在我的 webpack.config.js 中添加以下行
devServer: {
injectClient: false
},
以下是参考网址:https ://github.com/webpack/webpack-dev-server/issues/2484
不要忘记投票。谢谢。
推荐阅读
- swift - SwiftUI通过Navigationview推送视图在关闭工作表后弹出
- python - Pandas:如何识别 x 列中具有特定值的行,并将同一行中的其他值用作变量?
- r - 如何将ggplot2包装为R中的函数
- google-maps - 将 MarkerClustererPlus 添加到现有的 Google Maps API 嵌入式代码
- c++ - _Get_unwrapped 的含义?
- django - 如何将非字段相关的日期范围添加到 Django 管理表单
- pandas - 生成随机日期,其中另一个日期列之间的增量在 python 中呈指数分布
- java - 有没有办法在 IntelliJ 装订线中突出显示未保存或更改的行 - 更改跟踪
- database - 定期快照事实表 - 设计问题
- swift - 使用可编码删除核心数据并建立关系