简体   繁体   中英

Babel not transpiling JSX from files above current directory

I have a monorepo set up with a file structure like:

/root

  /-ProjectA

  /-ProjectB

  /-common

In /ProjectA, I have a React app which imports a file from /common. When I try to start it in the Webpack Dev Server, I get an error from Babel-Loader saying that there is a compilation error in the imported common file where the JSX starts.

If I move the common file into ProjectA and import from there, everything works fine so there is no problem in that specific file (plus it's a very simple contrived example at this point).

/common/index.js (this is the only files in this directory)

import React from 'react';
export default () => <span>Hello, World!</span>;

/ProjectA/index.js

import React from 'react';
import ReactDOM from 'react-dom';
import Hello from '../common';

const App = () => <div><Hello /></div>;
ReactDOM.render(<App />, document.querySelector('#root'));

/ProjectA/.babelrc

{
  "presets": [
    "@babel/preset-env",
    "@babel/preset-react"
  ]
}

/ProjectA/webpack.config.js

{
  test: /\.(js|jsx)$/,
  exclude: /node_modules/,
  include: [
    path.resolve('.'),
    path.resolve('../common'),
  ],
  use: {
    loader: 'babel-loader'
  }
}

/ProjectA/package.json

{
  "dependencies": {
    "react": "^16.8.6",
    "react-dom": "^16.8.6"
  },
  "devDependencies": {
    "@babel/core": "^7.5.4",
    "@babel/preset-env": "^7.5.4",
    "@babel/preset-react": "^7.0.0",
    "babel-loader": "^8.0.6",
    "html-loader": "^0.5.5",
    "html-webpack-plugin": "^3.2.0",
    "webpack": "^4.35.3",
    "webpack-cli": "^3.3.6",
    "webpack-dev-server": "^3.7.2"
  }
}

Why is babel unable to transpile files from outside the current directory? Is there a way around this or a problem in my configs maybe?

Add this line to webpack.config.js

 devServer: { contentBase: path.join(__dirname, "public") }

add this script to package.json

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

config.webpack.js(without styling loaders)
    module.exports = {
      entry: './src/app.js',
      output: {
        path: path.join(__dirname, 'public'),
        filename: 'bundle.js'
      },
      module: {
        rules: [{
          loader: 'babel-loader',
          test: /\.js$/,
          exclude: /node_modules/
        }, 
      devtool: 'cheap-module-eval-source-map',
      devServer: {
        contentBase: path.join(__dirname, 'public')
      }
    };

now this command should run your app.

npm run dev-server

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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