【问题标题】:Webpack/Babel-transformed .js file has wrong MIME type ('text/html' not 'text/javascript')Webpack/Babel 转换的 .js 文件具有错误的 MIME 类型('text/html' 不是 'text/javascript')
【发布时间】:2018-06-14 09:18:30
【问题描述】:

当为一个简单的“Hello World”react.js 组件运行 webpack/babel 和 node.js 时,转换后的 .js 文件显然没有作为正确的 MIME 类型返回:

Chrome 开发者工具反馈:

“拒绝执行来自 'https://example.com/dev/test-app/transformed.js' 的脚本,因为它的 MIME 类型 ('text/html') 不可执行,并且启用了严格的 MIME 类型检查。”

在缩减和更正配置文件并仔细阅读文档和 StackOverflow 答案后,我仍然无法解决此问题或发现此特定问题已在任何地方得到解决。 (任何见解都会受到重视和赞赏;我是 Node.js、Webpack、Babel 和 React.js 的新手。)

app/index_template.html:

<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Test App</title>
    <script type="text/babel" src="index.js"></script>
  </head>
  <body>
    <div id="app"></div>    
  </body>
</html>

app/index.js:

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

import HelloWorld from './components/HelloWorld.js';

ReactDOM.render(
  <HelloWorld />,
  document.getElementById('app')
);

app/components/HelloWorld.js:

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

class HelloWorld extends React.Component {
  constructor(props) {
    super(props);
  }

  render() {
    return <h1>Testing....</h1>;
  }
}    

export default HelloWorld;

package.json:

{
  "name": "test-app",
  "version": "0.0.0",
  "private": true,
  "scripts": {
    "build": "webpack",
    "start": "node server.js",
    "dev": "webpack && npm start"
  },
  "dependencies": {
    "axios": "^0.17.1",
    "body-parser": "~1.18.2",
    "cookie-parser": "~1.4.3",
    "debug": "~2.6.9",
    "express": "~4.15.5",
    "morgan": "~1.9.0",
    "pg": "^7.4.0",
    "pug": "2.0.0-beta11",
    "react": "^16.2.0",
    "react-dom": "^16.2.0",
    "serve-favicon": "~2.4.5"
  },
  "devDependencies": {
    "@babel/preset-env": "^7.0.0-beta.35",
    "babel-cli": "^6.26.0",
    "babel-core": "^6.26.0",
    "babel-loader": "^7.1.2",
    "babel-preset-env": "^1.6.1",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-react": "^6.24.1",
    "html-webpack-plugin": "^2.30.1",
    "nodemon": "^1.12.5",
    "webpack": "^3.10.0",
    "webpack-dev-server": "^2.9.7"
  }
}

webpack.config.js:

const path = require('path');
const webpack = require('webpack');

const HTMLWebpackPlugin = require('html-webpack-plugin');
const HTMLWebpackPluginConfig = new HTMLWebpackPlugin({
  template: path.join(__dirname, 'app/index_template.html'),
  filename: path.join(__dirname, 'app/index.html'),
  inject:   'body'
});


var fs = require('fs');
var nodeModules = {};

fs.readdirSync(path.resolve(__dirname, 'node_modules'))
    .filter(x => ['.bin'].indexOf(x) === -1)
    .forEach(mod => { nodeModules[mod] = `commonjs ${mod}`; });

// Ref: https://stackoverflow.com/questions/31102035/how-can-i-use-webpack-with-express


module.exports = [
  {
    name: 'server',
    entry: path.join(__dirname, 'server.js'),
    target: 'node',
    output: {
      path: path.join(__dirname, 'dist/server'),
      filename: 'server.js'
    },
    externals: nodeModules
  },
  {
    name: 'client',
    entry: path.join(__dirname, 'app/index.js'),
    output: {
      path: path.join(__dirname, 'app'),
      filename: 'transformed.js'
    },
    module: {
      loaders: [
        {
          test: /\.jsx?$/,
          exclude: /node_modules/,
          loader: 'babel-loader',
          query: {
            presets: ['react', 'env']
          }
        }
      ]
    },
    plugins: [HTMLWebpackPluginConfig]
  }
];

[编辑:]

问题出在 Node.js 级别;编辑了我的 server.js 以显式传递 .js 文件的 MIME 类型:

[....]

var app = express();
[....]

app.get('*', function (req, res) {
  var p = req.path.replace(/^\//, '').replace(/\/$/, '');
  if (p && p.endsWith('.js')) {
    var options = { headers: {'content-type': 'application/javascript'} };
    res.sendFile(path.join(__dirname, 'app', p), options);
  } else
    res.sendFile(path.join(__dirname, 'app', 'index.html'));
});

(这让我觉得有点笨拙;我以后可能会尝试想出一个更优雅的解决方案。)

【问题讨论】:

    标签: node.js reactjs webpack mime-types babeljs


    【解决方案1】:

    我的假设可能是错误的,但该错误与对“example.com”的请求有关 - 您只是在这里使用它来说明请求吗?如果没有,那么您需要替换为您当前的域,例如“http://localhost:3000/dev/test-app/transformed.js”。 Example.com 只会返回 HTML 内容作为演示。

    【讨论】:

    • 不,我不这么认为。出于隐私原因,我用“example.com”代替了我的域。不过,谢谢。
    • mime 类型将由服务器设置 - 您使用的是 Nginx 还是类似于 nodejs 的代理?你能展示你用来托管transformed.js的服务器配置/脚本吗?
    • 感谢您为我指明了正确的方向并让我重新检查了我的 Node.js 代码;请参阅上面的编辑以获取我的修复。再次感谢!
    猜你喜欢
    • 2018-12-13
    • 1970-01-01
    • 2021-04-07
    • 2021-03-17
    • 2016-08-30
    • 2021-04-08
    • 2021-03-27
    • 2014-05-27
    • 2018-03-30
    相关资源
    最近更新 更多