无法使用 Webpack DevServer 接收我的 js 和 css 文件

Can't receive my js and css files with Webpack DevServer

我有以下项目结构:

root
|_app
| |_index.html
|_dist
| |_js
| | |_app.js
| |_styles
|   |_app.css
|_src
| |_js
| | |_models
| | | |_model.ts
| | |_app.ts
| |_styles
|   |_normalize.css
|   |_style.scss
|_package.json
|_webpack.config.js

目前我的 Webpack 配置确实将 SCSS 转换为 CSS 并将其复制到 dist 文件夹。它对 JS 文件做同样的事情(虽然目前不将 .ts 编译为 .js,IDE 会处理它)。

在我的 index.html 文件中,我有以下 CSS 和 JS 的声明:

<link rel="stylesheet" href="../dist/styles/app.css">
<script src="../dist/js/app.js" type="text/javascript"></script>

这是我的 Webpack 配置:

module.exports = {
    context: path.resolve(__dirname, 'src'),

    entry: {
        app: [
        './js/app.js',
        ],
    },

    output: {
        filename: 'js/[name].js',
        path: path.resolve(__dirname, 'dist'),
        publicPath: '../'
    },

    devServer: {
        contentBase: './app'
    },

   ...
}

当我的应用程序文件夹位于 src 文件夹中时,它工作得很好。但是我曾经将它移到根文件夹并相应地更改了 devServer 配置 - 浏览器找不到 CSS 和 JS。我经常收到此错误,例如:

Loading failed for the <script> with source “http://localhost:8080/dist/js/app.js”.

无论我尝试了什么(更改 devServer contentBase、更改 JS 和 html 中的 CSS 路径等)- 它要么无法加载 index.html 或加载它,但是找不到 CSS 和 JS 文件。

我需要更改什么才能使其正常工作?

在 WDS 为您的包提供服务的浏览器中查看。通常 js 和 css 文件的 path 相同,filename 决定每个输出包的 名称

这个例子可能会帮助你前进:

output: {
  path: path.resolve(__dirname, 'public/assets'),
  filename: '[name].js',
  publicPath: 'http://localhost:8080/assets/'
}

阅读 output configuration for more info and check if you are using sass and ts 加载程序。