繁体   English   中英

webpack错误无法解决“ ./src”

[英]webpack error cant resolve './src'

我是webpack的新手。 我正在学习使用webpack反应并为其构建环境。

我有webpack-config.js

var path = require('path');


module.exports = {
    mode: 'production',
    entry: './script.js',
    output: 
    {
        path: path.resolve(__dirname, 'src'),
        filename: 'transpiled.js'
    },
    module: 
    {
        loaders: [
        {
            test: /\.js$/,
            loader: 'babel-loader',
            exclude: /node_modules/,
            query:
            {
                presets: ['es2015','react']
            }
        }
        ]
    }
}

和script.js

    import React from 'react';
import ReactDOM from 'react-dom';

ReactDOM.render(
    <h1>Hello world</h1>    
    document.getElementByIdName('first')
);

和index.html

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
    <div class="first"></div>
    <script src="transpiled.js"></script>
</body>
</html>

在我写的Pakage.json文件中

"scripts": {
    "it": "webpack-dev-server --hot" 
  },

但是当我使用“ npm run it”运行npm时,它显示了以下错误

配置中的警告尚未设置“模式”选项。 将“模式”选项设置为“开发”或“生产”以启用该环境的默认设置。 多-dev-derver /客户端中的错误? http:// localhost:8080 webpack / hot / dev-server ./src找不到模块:错误:无法在D:\\ React Js \\ LearnReact'@multi -dev-derver / client中解析'./src'吗? http:// localhost:8080 webpack / hot / dev-server ./src i?wdm ?:编译失败。

请帮助我,我真的很困惑,想知道解决方案。

您需要将--config选项传递给webpack-dev-server

webpack-dev-server --config path/to/webpack.config.js

还要在基本配置中将模式设置为development模式,稍后在进行生产构建时可以覆盖它。

还要确保您的./script.js文件位于项目的根目录下,即package.json旁边,因为该文件路径与npm脚本执行有关。

根据此配置-> path: path.resolve(__dirname, 'src') ,假设您的webpack.config.js文件位于( webpack.config.js目录下,则所有已构建资产最终都将位于项目根目录下的src文件夹中。此路径相对于您的配置文件)。 实际的文件夹仅在production中生成,在development资产中存储在内存中。

您可能还需要设置publicPath

output: {
  ...
  publicPath: '/'
}

我还建议您使用html-webpack-plugin因为这样可以为您解析js文件的正确路径。

var HtmlWebpackPlugin = require('html-webpack-plugin');

...
plugins: [
  new HtmlWebpackPlugin({
    filename: 'index.html', // name of file that will be outputted to 'src' when built
    template: // path to your html file relative to config
    inject: true
  })
]

然后,您不必包括脚本的路径,因此您的html文件如下所示:

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
    <div class="first"></div>
</body>
</html>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM