首页 > 解决方案 > Can't receive my js and css files with Webpack DevServer

问题描述

I have the following project structure:

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

Currently my Webpack configuration does transform the SCSS to CSS and copies it to dist folder. It does the same with JS file (though currently doesn't compile .ts to .js, the IDE takes care of it).

In my index.html file I have the following declaration of CSS and JS:

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

And here's my Webpack config:

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'
    },

   ...
}

When my app folder was inside the src folder it worked just fine. But I once I moved it out to root folder and changed the devServer configuration accordingly - the browser can't find the CSS and JS. I'm constantly getting this error, for example:

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

No matter what I tried (changing devServer contentBase, changing JS and CSS path in html etc) - it either can't load the index.html or loads it, but can't find the CSS and JS files.

What do I need to change to make it work?

标签: javascripthtmlwebpackwebpack-dev-server

解决方案


Take a look in the browser where WDS serves your bundles. Usually the path is the same for js and css files and the filename determines the name of each output bundle.

This example may help you to move forward:

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

Read the output configuration for more info and check if you are using sass and ts loaders.


推荐阅读