你好,我升级到以下版本的Webpack 5:
// package.json
"webpack": "^5.11.1",
"webpack-cli": "^4.3.1",
"webpack-dev-server": "^4.0.0-beta.0",
我用以下命令启动dev服务器:
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
可以找到有问题的文件这里..。即使有错误,一切似乎都运行得很好。但是在开发时保留这个错误是很糟糕的。
关于如何摆脱这个错误的任何建议,并提供window对象添加到webpack dev服务器?
发布于 2021-01-21 18:54:07
如果你可以打补丁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')();
}
})()
那么这应该是可行的。
https://stackoverflow.com/questions/65626352
复制相似问题