未定义webpack开发服务器v4-窗口



你好,我升级到了Webpack 5,版本如下:

// package.json
"webpack": "^5.11.1",
"webpack-cli": "^4.3.1",
"webpack-dev-server": "^4.0.0-beta.0",

我使用以下配置启动带有webpack-dev-server -d source-map --mode=development的开发服务器:

// webpack.config.json
{
entry,
output: {
filename: '[name].[fullhash].js',
path: path.resolve(__dirname, 'build'),
publicPath: '/',
},
resolve: {
extensions: [
'.js',
'.jsx',
'.ts',
'.tsx',
],
alias,
},
context: path.resolve(__dirname, 'src'),
devServer: {
static: path.resolve(__dirname, 'build'),
public: 'localhost:3000',
open: true,
historyApiFallback: true,
port: 3000,
proxy: {
'^/': 'http://localhost:3000'
},
},
plugins: [
new WebpackDotenv(),
new HtmlWebpackPlugin({
template: 'index.html',
collapseWhitespace: true,
removeComments: true,
}),
new MiniCssExtractPlugin({
filename: 'styles.css',
}),
new SVGSpritemapPlugin(
'/assets/icons',
{
output: {
filename: 'spritemap.svg',
}
}
),
],
stats: {
assets: true,
assetsSort: 'size',
all: false,
errors: true,
colors: true,
performance: true,
timings: true,
},
optimization: {
minimizer: [
new OptimizeCSSAssetsPlugin({}),
new TerserPlugin({
// Use multi-process parallel running to improve the build speed
// Default number of concurrent runs: os.cpus().length - 1
parallel: true,
// Enable file caching
extractComments: false,
}),
new UglifyJsPlugin({
uglifyOptions: {
output: {
comments: false,
}
}
}),
],
},
module: {
rules: [
{
test: /.ts(x?)$/,
exclude: /node_modules/,
use: {
loader: 'swc-loader',
options: {
sync: true
}
},
},
{
// TODO: somehow the sourcemap is not being generated properly
test: /.s(a|c)ss$/,
use: [
{
loader: 'style-loader',
},
{
loader: 'css-loader',
options: {
sourceMap: true,
}
},
{ loader: 'resolve-url-loader' },
{
loader: 'postcss-loader',
options: {
postcssOptions: {
plugins: [
require('autoprefixer'),
],
},
},
},
{
loader: 'sass-loader',
}
],
},
{
test: /.css$/,
use: [
MiniCssExtractPlugin.loader,
'css-loader',
],
},
{
test: /.(ttf|eot|woff|woff2)$/,
use: {
loader: 'file-loader',
options: {
name: '[name].[ext]',
outputPath: 'fonts/',
publicPath: '/fonts',
esModule: false,
},
},
},
{
test: /.(gif|png|jpe?g|svg)$/i,
use: [
{
loader: 'file-loader',
options: {
name: '[name].[ext]',
outputPath: 'images/',
publicPath: '/images',
}
}
],
},
],
},
devtool: 'source-map',
}

一切都很好,除了我收到以下错误:

// browser console
Uncaught ReferenceError: window is not defined
at Object.../node_modules/webpack-dev-server/client/default/index.js

有问题的文件可以在这里找到。一切似乎都很好,即使有错误。但在开发过程中保留这个错误感觉很糟糕。

关于如何消除此错误并向webpack dev服务器提供window对象,有什么建议吗?

如果可以修补index.ts并将所有窗口调用替换为:

(() => {
if (typeof self !== 'undefined') {
return self;
} else if (typeof window !== 'undefined') {
return window;
} else if (typeof global !== 'undefined') {
return global;
} else {
return Function('return this')();
}
})()

那么这应该行得通。

这里的问题是,在我的entry变量中,我得到了两件事。一个是应用程序本身,另一个是它的service-worker。后期结合开发模式是造成错误的原因。所以我现在只是在注册service-worker之前检查process.env.NODE_ENV !== 'development'

不是一个真正的解决方案,但对于我的用例来说已经足够了。

最新更新