javascript - 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?
解决方案
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.
推荐阅读
- javascript - 如何比较嵌套数组中的元素
- java - 检测编号表上的缺失记录
- c - 短到字符铸造
- java - 使用 .toArray() 将 ArrayList 转换为 Int [] 数组?或者...?
- angular - 根据位置找出给定数字的小数分隔符
- visual-studio-code - How can I remove this Git helper button bar in VSCode?
- python - Load data from Google Datastore to Google Cloud ML Engine
- javascript - 如何“要求”一个 xml 文件(由 webpack 加载)以读取 javascript 中的 xml 内容
- oracle - 通过脚本动态重命名索引和约束
- java - How to show an input is invalid in this java code